MATLAB Making MATLAB Code Efficient: A 2xN Vector

AI Thread Summary
To optimize MATLAB code for calculating a 2xN vector, combining two operations into a single line is possible. For a 2-row vector, the function `bsxfun` can be used as follows: `acc1 = bsxfun(@times, rc, [A; B]);`. If the vectors have more than two rows, the code should be adjusted to `acc1(1:2, :) = bsxfun(@times, rc(1:2, :), [A; B]);`. For versions of MATLAB that do not support `bsxfun`, an alternative is to use `repmat` with the syntax: `acc1 = rc .* repmat([A; B], 1, size(rc, 2));`. This approach effectively combines the operations while maintaining efficiency.
Meurig
Messages
6
Reaction score
0
Hi everyone,

I'm trying to make my MATLAB code run as efficiently as possible.

II have a 2xN vector designated like so:
acc1(1,:) = A*rc(1,:);
acc1(2,:) = B*rc(2,:);

where A and B are scalars,.

Is it possible to combine these two into a single line of code?

Cheers
 
Physics news on Phys.org
If acc1 and rc have only 2 rows, then you can use: acc1=bsxfun(@times, rc, [A; B]);

If acc1 and/or rc have more than 2 rows, then: acc1(1:2, :)=bsxfun(@times, rc(1:2, :), [A; B]);

Documentation for http://www.mathworks.com/help/techdoc/ref/bsxfun.html"

Another way to do it (if your version of Matlab doesn't have bsxfun): acc1=rc.*repmat([A; B], 1, size(rc, 2));
 
Last edited by a moderator:
Thanks very much!
 

Similar threads

Replies
8
Views
2K
Replies
32
Views
4K
Replies
5
Views
2K
Replies
4
Views
1K
Replies
10
Views
3K
Replies
1
Views
2K
Back
Top