How can I execute a calculation multiple times using matrix elements as variables?
6 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (3 件)
Stephen23
2015 年 3 月 3 日
編集済み: Stephen23
2015 年 3 月 3 日
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!
Ortinomax
2015 年 3 月 3 日
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.
参考
カテゴリ
Help Center および File Exchange で Environment and Settings についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!