for loop, change matrix dimensions

7 ビュー (過去 30 日間)
Giovanni Gardan
Giovanni Gardan 2020 年 8 月 5 日
回答済み: Rik 2020 年 8 月 5 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by