Matlab: How to create a loop for reading an matrix based on specific column values

StackOverflow https://stackoverflow.com/questions/23672879

  •  23-07-2023
  •  | 
  •  

Question

I have a matrix as follows:

merged = 

'A05'    'a001'
'A06'    'a001'
'B05'    'a001'
'B06'    'a001'
'C01'    'a001'
'C02'    'a001'
'C03'    'a001'
'C04'    'a001'
'C05'    'a001'
'C06'    'a001'
'D01'    'a001'
'D02'    'a001'
'D03'    'a001'
'D05'    'a001'
'D04'    'a001'
'D06'    'a001'
'A03'    'a002'
'A04'    'a002'
'B03'    'a002'
'B04'    'a002'

Is it possible to make a loop, which read a001 rows first and then read a002 in the second round?

Thanks, Woody

Was it helpful?

Solution

Remember that loop-solutions are in general slow in Matlab, but if you want it, here is a variant

tags = {'a001','a002'};
for i=1:length(tags)
  M = merged(strcmp(merged(:,2),tags{i}));
end

then you can operate on M in each itteration

OTHER TIPS

Find the rows that contains 'a001'. Then select all columns for those rows

A = merged(find(merged(:,2)=='a001'),:)

A = merged(find(merged(:,2)=='a002'),:)

or you can sort them accordinf to the second column and then apply your for loop

sorted = sortrows(merged,2);
for i=1:1:size(sorted,1)
    % Do what you need
end

Info on sortrows()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top