How to delete a row of a table in a loop while indices are changing
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Johnny
am 28 Nov. 2016
Kommentiert: Johnny
am 29 Nov. 2016
I would like to do a comparison of a value with a previous value of a variable which appears after every sixth values. And if this variable is the same, I would like to delete the whole row. But when I delete, the indices change and it no longer appears after sixth values. How do I delete a row in a loop when the indices are changing?
for i=7:length(table)
if isequal(table(i,9),table(i-6),9)
table(i,:)=[];
end
end
0 Kommentare
Akzeptierte Antwort
Ryan Smith
am 28 Nov. 2016
Your provided code is a little unclear in what you want to compare. Your conditional should always return 0, as it is:
if isequal(table(i,9),table(i-6))
Assuming you mean:
if isequal(table(i,9),table(i-6,9))
Furthermore, table(i,9) = []; just deletes a single cell of table, not the entire row.
Nonetheless, you might could try unique(). https://de.mathworks.com/help/matlab/ref/unique.html
But unique will compare your entire list/table. It might be best to just use a second array:
A = table(1:6,:);
j = 7;
for i=7:length(table)
if table(i,9) ~= table(i-6,9)
A(j,:)=table(i,:);
j = j + 1;
end
end
Hope this helps!
2 Kommentare
Weitere Antworten (1)
Guillaume
am 28 Nov. 2016
From your comments, I'm going go out on a limb and assume that your (very badly named) table variable is actually not a table but a cell array. It can't be a table since the length function is not defined for tables.
Even for matrix and cell array, where length is defined, you shouldn't be using it since it will return either the number of rows or columns depending on which is greater. Use size with an explicit dimension.
If you want to use a loop to delete your rows, you have to store which rows you want to delete in the loop and perform the deletion at the end of the loop.
%somevariable: your badly named table variable renamed to something better
deleterow = false(size(somevariable, 1) %allocate array which tells us which row to delete
for row = 7: size(somevariable, 1) %use size instead of length
%to access the content of a cell of a cell array use {} not ().
%you can then compare with == assuming the content is scalar
if somevariable{i, 9} == somevariable{i-6, 9} %if not scalar then use isequal
deleterow(row) = true;
end
end
somevariable(deleterow, :) = []; %and delete all rows at once
If the content of column 9 is scalar, you don't even need a loop:
deleterow = cell2mat(somevariable(1:end-7)) == cell2mat(somevariable(7:end));
somevariable(deleterow, :) = [];
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!