How can I automate a process for n times?

4 次查看(过去 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.

回答(1 个)

Chunru
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]
J = 6×5
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
a = 14
a = 15
a = 48
a = 44
a = 48
a = 125
  3 个评论
Walter Roberson
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;
Mikel Gonzalez Bribiesca
Thank you, yes that works! Crazy how simple you make it

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by