Introducing a bug in the for loop

3 views (last 30 days)
Chao Zhang
Chao Zhang on 6 Jun 2021
Answered: Chetan on 1 Mar 2024
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.

Answers (1)

Chetan
Chetan on 1 Mar 2024
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!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!