for loop, change matrix dimensions

5 visualizzazioni (ultimi 30 giorni)
Giovanni Gardan
Giovanni Gardan il 5 Ago 2020
Risposto: Rik il 5 Ago 2020
I have a matrix (A) which is 2156x25 in dimension.
I want to find if there are more than one equal element in column 2 that in first column have the same values (=67). For these elements I want to keep the corresponding first row and sum to this row the numbers of the third and fourth column of all these elements. Then I want to delete from the matrix the elements of the rows with same elements in second and first column(except the first row).
I have a problem in my code: the message is: Index in position 1 exceeds array bounds (must not exceed 958).
Why? Is this Because the matrix dimension change? Could I do something?
% Input: A is a matrix which is 2156x25
for k = 1:size(A,1)
dop = find(A(k,2) == CAR_GEN(:,2));
if size(dop,1) > 1
ccc = find(A(dop,1) == 67);
if(size(ccc,1)) > 1
A(ccc(1),3) = sum(A(ccc,3));
A(ccc(1),4) = sum(A(ccc,4));
A(ccc(2:end),:)= [];
end
end
end

Risposta accettata

Rik
Rik il 5 Ago 2020
In general you're better off using a separate logical array to mark which rows should be deleted and doing the deletion in one go. If you want to keep your current code structure, a while loop is a better choice:
k=0;
while k<size(A,1)
k=k+1;
dop = find(A(k,2) == CAR_GEN(:,2));
if size(dop,1) > 1
ccc = find(A(dop,1) == 67);
if(size(ccc,1)) > 1
A(ccc(1),3) = sum(A(ccc,3));
A(ccc(1),4) = sum(A(ccc,4));
A(ccc(2:end),:)= [];
end
end
end

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by