for loop, change matrix dimensions

5 次查看(过去 30 天)
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

采纳的回答

Rik
Rik 2020-8-5
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by