How can I execute a calculation multiple times using matrix elements as variables?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (3)
Stephen23
el 3 de Mzo. de 2015
Editada: Stephen23
el 3 de Mzo. de 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 comentarios
Stephen23
el 3 de Mzo. de 2015
Editada: Stephen23
el 3 de Mzo. de 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.
Ortinomax
el 3 de Mzo. de 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
el 3 de Mzo. de 2015
D = [1 2 3;4 5 6];
out = D(:,1).*cos(D(:,2)+50*D(:,3));
0 comentarios
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!