How can I execute a calculation multiple times using matrix elements as variables?

18 views (last 30 days)
Say I have a matrix D = [1 2 3;4 5 6], where the columns are named A, B, and C.
Now I have the formula X(i) = A(i) + B(i) + C(i), where i is the 'i'th row.
So X(1) = D(1,1) + D(1,2) + D(1,3) = 1 + 2 + 3, and X(2) = D(2,1) + D(2,2) + D(2,3) = 4 + 5 + 6
Now I want Matlab to return all the X(i) functions as X(1), X(2) (or X1, X2) by creating, for example, a loop structure.
I could create all formula's individually, but I would like to figure out how to do it more efficiently since I have a matrix of 200 rows.

Answers (3)

Stephen23
Stephen23 on 3 Mar 2015
Edited: Stephen23 on 3 Mar 2015
This is a great example of where vectorization would be the best way to get this result. Most inbuilt MATLAB functions can operate on whole arrays at once, without requiring any loops: this is much faster to run, and the code required is much neater too! Using vectorized code is also much more expandable than using loops, so even if the data gets much larger, it will still be the fastest and most optimal way to calculate.
For your example, we can simply use sum :
>> D = [1 2 3; 4 5 6];
>> sum(D,2)
ans =
6
15
And there is your result! Note that this uses sum's optional second input to specify which dimension we want to sum along.
Of course if you are writing your own functions then you can (and should) consider writing them to perform operations completely vectorized. Keep this in mind: in MATLAB loops are the second choice, not the first!
  2 Comments
Vandero
Vandero on 3 Mar 2015
Thanks for your reply Stephen! Though it is not exaclty what I'm looking for, I should've been a bit more specific.
Unfortunately the formula is a bit more complex than just a sum, it looks a bit like this:
X(1) = D(1,1)*cos(D(1,2)+D(1,3)*50);
meaning the sum function isn't applicable.
Stephen23
Stephen23 on 3 Mar 2015
Edited: Stephen23 on 3 Mar 2015
Sure, we can vectorize that too:
>> D = [1 2 3; 4 5 6];
>> X = D(:,1).*cos(D(:,2)+D(:,3)*50)
X =
0.3590
-3.8598
Where D(:,1) is all values in the first column, etc, so the calculation can still be performed on all rows simultaneously.

Sign in to comment.


Ortinomax
Ortinomax on 3 Mar 2015
The anwser of Stephen Cobeldick is great.
But if you want to perform another calculation like below on each lines :
X(1) = D(1,1) + (D(1,2)*D(1,3))
You could think of this kind of notation :
X= D(:,1) + (D(:,2).*D(:,3))
Where D(:,x) are columns of D.

Andrei Bobrov
Andrei Bobrov on 3 Mar 2015
D = [1 2 3;4 5 6];
out = D(:,1).*cos(D(:,2)+50*D(:,3));

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!