Introducing a bug in the for loop

1 次查看(过去 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