Azzera filtri
Azzera filtri

How can I automate a process for n times?

5 visualizzazioni (ultimi 30 giorni)
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.

Risposte (1)

Chunru
Chunru il 4 Ago 2022
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 Commenti
Walter Roberson
Walter Roberson il 4 Ago 2022
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 il 4 Ago 2022
Thank you, yes that works! Crazy how simple you make it

Accedi per commentare.

Categorie

Scopri di più su Sparse Matrices in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by