Info
此问题已关闭。 请重新打开它进行编辑或回答。
Trying to code nested loops, not checking all cells
1 次查看(过去 30 天)
显示 更早的评论
Hi all,
I am working on a project that needs to check columns to see if they have duplicate strings, which needs to continue through checking after finding a duplicate but also then to iterate towards other duplicates.
I have a sample matrix:
and this has a number of duplicates along the top. What needs to happen is for each duplicate, it moves the '1' in the column to the first occurance of that string, replaces the duplicate with 0, and replaces the column name. Something like this (but this isnt quite right, its what I have right now, see column 4, 6, 9, 10 are the same but nothing has happened):
As you can see, it is doing a part of what I want, but it is not going through all of them. My code:
matrix=matrix1; //creates duplicate matrix to work in
[no_patients, no_mutations] = size(matrix);
for column_index = 2:no_mutations //first for loop, going through all columns
for column_index2 = 3:no_mutations //second for loop, going through all columns +1 from previous.
if (strncmp(matrix{1, column_index}, matrix{1,column_index2},28)==1) //check the strings are the same
for row_index = 2:no_patients //go through rows in that column to find the 1 and clean up
if matrix{row_index,column_index2} == 1
matrix{row_index,column_index} = 1;
matrix{1,column_index2} = duplicate; //sets the string to 'duplicate'
matrix{row_index,column_index2} = 0;
end
end
end
end
break; // Without this break, it doesnt work as expected.
end
As noted there, without that break, it doesnt work as expected at all:
I would really appreciate some advice on what i have wrong with my code. Coding is not my strong point and this does need to work on a very large matrix, so i hope i am not too far off.
Thanks for any help!!
0 个评论
回答(1 个)
Ajith Krishna Kanduri
2020-6-18
Hi Kane,
I can see you are using strncmp function i.e,comparing upto 28 characters,you can use strcmp() function to check if the strings are similar.
And I can see you are changing the coloumn name to "duplicate",if you find a cell with value "1" in that coloumn.You can change right after comparing the strings.Since if there are no ones in that coloumn then the name would not change.
And I can see the root issue is that after the 1st loop some of the coloum names are set to duplicate.You need not compare those again with other coloumns.
0 个评论
此问题已关闭。
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!