3

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.

4
  • You surely mean c1 * exp(a1 *x) * b11 + c2 * exp(a2 * x) * b21 + ...? Commented Nov 28, 2013 at 23:37
  • Yes, sorry, I'll correct my question Commented Nov 28, 2013 at 23:38
  • Which size should your result be (for the given example values)? Commented Nov 28, 2013 at 23:40
  • For a particular x , a 1x2 array. If I use a Nx1 array, it should give a Nx2 array with each column for different x Commented Nov 28, 2013 at 23:45

2 Answers 2

3

What about this:

results = arrayfun(ff, x ,  'UniformOutput', false);
results{:}
Sign up to request clarification or add additional context in comments.

9 Comments

This seems to work perfectly, thank you. What does the {:} do? Since with the first command I get something like [1x2 double]
@DavidWinchester arrayfun returns a cell. results{:} will just output the results.
@DavidWinchester Yes, use results = cell2mat(results.'); to get an Nx2 matrix
@DavidWinchester .' is matrix or array transposition. It turns the 1x4 array of 1x2-vectors into a 4x1 array of the same 1x2-vectors; and then cellmat puts that into matrix (4x2) form
@DavidWinchester Without the dot it also applies complex conjugation. Careful with that if you apply it for example to a matrix of complex numbers.
|
1

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.

1 Comment

Yes, someone pointed that out before, I corrected my question. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.