Making MATLAB Code Efficient: A 2xN Vector

Click For Summary
SUMMARY

This discussion focuses on optimizing MATLAB code for handling a 2xN vector efficiently. The user seeks to combine two operations into a single line of code using the bsxfun function. The recommended solution is acc1=bsxfun(@times, rc, [A; B]) for vectors with exactly two rows. For vectors with more than two rows, the code acc1(1:2, :)=bsxfun(@times, rc(1:2, :), [A; B]) is suggested. An alternative method using repmat is also provided for users with older MATLAB versions.

PREREQUISITES
  • Familiarity with MATLAB programming
  • Understanding of vector operations in MATLAB
  • Knowledge of the bsxfun function in MATLAB
  • Experience with the repmat function in MATLAB
NEXT STEPS
  • Research the bsxfun function in MATLAB for advanced vector operations
  • Explore vectorization techniques in MATLAB to improve code efficiency
  • Learn about MATLAB's element-wise operations for performance optimization
  • Investigate the differences between bsxfun and repmat for handling arrays
USEFUL FOR

MATLAB programmers, data analysts, and engineers looking to enhance the performance of their vector operations in MATLAB.

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
5
Views
3K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
7K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K