Domanda

I have an anonymous function:

a = [1, 2];
b = [1, 1; 3, 2];
c = [4, 2];
ff = @(x) (exp(a .* x) .* c) * b;

The problem is that, when I have an array, say x = [1,2,3,4] , Matlab thinks that I'm using the array and multiplying that in the exponential, and not each element. The error is

Error using .* Matrix dimensions must agree.

Error in @(x)(exp(a.*x).*c)*b

I just need something like c1 * exp(a1 *x) * b11 + c2 * exp(a2 * x) * b21 + ...

I can use a for loop if I want to evaluate the function for each x element and it gives me the answer that I want, but I think there may be an easiest way, like when we can use simply f(x) and get an array with each element evaluated in the function. I tried using arrayfun but I get the same error. I want to skip for loops since they are slow for bigger matrices.

È stato utile?

Soluzione

What about this:

results = arrayfun(ff, x ,  'UniformOutput', false);
results{:}

Altri suggerimenti

Use arrayfun(ff,x,'UniformOutput',false) to return the 4 cells corresponding to your four outputs. I think it should be c1 * exp(a1 *x) * b11 + c2 * exp(a2 * x) * b21 + ... otherwise you need to transpose your b matrix before the multiplication.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top