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!