How can I execute a calculation multiple times using matrix elements as variables?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposte (3)
Stephen23
il 3 Mar 2015
Modificato: Stephen23
il 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.
>> 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 Commenti
Ortinomax
il 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.
Vedere anche
Categorie
Scopri di più su Environment and Settings in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!