How can I automate a process for n times?
5 ビュー (過去 30 日間)
古いコメントを表示
So basically I have a working code to calculate some values from a Matrix.
My problem is that I had to input each one manually, and I think there most be a way to automate it so I can reduce the amount of code needed.
I'll show 2 instances in which I'd like to do this, (both of them I believe should have the same "solution")
As I said I use a Matrix
J = [14 0 0 0 0; 15 0 0 0 0; 16 16 16 0 0; 22 22 0 0 0; 24 24 0 0 0; 25 25 25 25 25]
Lr = length ( J(:,1) );
Then I extract each row individually the following way
r1 = J(1,:);
r2 = J(2,:);
r3 = J(3,:);
r4 = J(4,:);
r5 = J(5,:);
r6 = J(6,:);
Which is just not very efficient.
My idea of a solution would be something like this
for i = 1:Lr
r(i) = J(i,:)
end
But that gives me the following error.
"Unable to perform assignment because the indices on the left side are not compatible with the size of the right side."
(Which to be fair, I'm not sure what it means or how to solve it)
I would like to find a way to automate this, and then later on being able to call each value, so each iteration saves itself and would allow me to use it later on, as I do here. (Which also needs to be automated)
nr1 = nnz(r1);
nr2 = nnz(r2);
nr3 = nnz(r3);
nr4 = nnz(r4);
nr5 = nnz(r5);
nr6 = nnz(r6);
Thank you so much if anyone reads all the way.
0 件のコメント
回答 (1 件)
Chunru
2022 年 8 月 4 日
J = [14 0 0 0 0; 15 0 0 0 0; 16 16 16 0 0; 22 22 0 0 0; 24 24 0 0 0; 25 25 25 25 25]
Lr = size(J,1);
for i = 1:Lr
row = J(i,:);
% Do something with row below
a = sum(row)
end
3 件のコメント
Walter Roberson
2022 年 8 月 4 日
for i = 1:Lr
row(i,:) = J(i,:);
end
But that is the same as
row(1:Lr,:) = J(1:Lr,:);
and when Lr is the number of rows in J like you have in your code, that simplifies to
row = J;
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!