필터 지우기
필터 지우기

How can I automate a process for n times?

조회 수: 5 (최근 30일)
Mikel Gonzalez Bribiesca
Mikel Gonzalez Bribiesca 2022년 8월 4일
댓글: Mikel Gonzalez Bribiesca 2022년 8월 4일
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
Mikel Gonzalez Bribiesca 2022년 8월 4일
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