# How can I automate a process for n times?

2 次查看（过去 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 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 个评论显示隐藏 2更早的评论
Thank you, yes that works! Crazy how simple you make it

### 类别

Find more on Matrix Indexing in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by