필터 지우기
필터 지우기

Introducing a bug in the for loop

조회 수: 4 (최근 30일)
Chao Zhang
Chao Zhang 2021년 6월 6일
답변: Chetan 2024년 3월 1일
M_ROCK = rock;
M_ROCK = array2table(M_ROCK,'VariableNames',G_Value.Properties.VariableNames);
%Enter the number of rock types and then create the corresponding
%ore matrixs,after determining the multiple rock types
num=input('Please enter the number of rock types:');
%Setup initial ore and waste matrix respectively
M_ORE = zeros(R1,C1,num);
M_WASTE = zeros(R1,C1);
M_WASTE = array2table(M_WASTE,'VariableNames',M_ROCK.Properties.VariableNames);
STR = cell(1,num);
for i = 1 : length(rock)
for j = 1 : num
STR{j} = sprintf('r%d_mill_tonnage',j);
if table2array(M_ROCK(i,STR{j})) > 0
M_ORE(i,:,j) = table2array(M_ROCK(i,:));
else
M_WASTE(i,:) = M_ROCK(i,:);
M_WASTE(M_WASTE{:, STR{j}} > 0, :) = [];
end
end
end
I think i introduced a bug in the above code, I assume that STR{j}>0 (i.e. 'r1_mill_tonnage' or 'r2_mill_tonnage'), the row will be [ ], and transfer others values from M_ROCK to M_WASTE, but the data in the last row shown in the figure below is not [ ] . And I cannot deal with this.

답변 (1개)

Chetan
Chetan 2024년 3월 1일
I understand that you're attempting to divide M_ROCK table data into M_ORE and M_WASTE based on user input for rock types. The issue is with deleting M_WASTE rows within the loop, which can misalign indices. To fix this, accumulate row indices to delete first, then remove them after looping.
Here's a revised version of your code:
M_ROCK = rock;
M_ROCK = array2table(M_ROCK,'VariableNames',G_Value.Properties.VariableNames);
%Enter the number of rock types and then create the corresponding
%ore matrixs, after determining the multiple rock types
num=input('Please enter the number of rock types:');
%Setup initial ore and waste matrix respectively
M_ORE = zeros(R1,C1,num);
M_WASTE = zeros(R1,C1);
M_WASTE = array2table(M_WASTE,'VariableNames',M_ROCK.Properties.VariableNames);
STR = cell(1,num);
to_remove = []; % Initialize an array to keep track of rows to remove
for i = 1 : length(rock)
for j = 1 : num
STR{j} = sprintf('r%d_mill_tonnage',j);
if table2array(M_ROCK(i,STR{j})) > 0
M_ORE(i,:,j) = table2array(M_ROCK(i,:));
else
M_WASTE(i,:) = M_ROCK(i,:);
if table2array(M_WASTE(i,STR{j})) > 0
to_remove = [to_remove; i]; % Mark row for removal
end
end
end
end
M_WASTE(to_remove, :) = []; % Remove all marked rows at once
Refer to the following MathWorks Documentation :
Hope it Helps!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by