requirement Switch & Case expression with matrix

7 views (last 30 days)
shin hsu
shin hsu on 29 May 2019
Answered: shin hsu on 29 May 2019
Is there a way to get aound the scalar and vector requirement for switch/ case expressions?
I have a coordinates matrix, coors = [x1 y1; x2 y2; x3 y3] and would like find out if they match a pre-defined list; for instance,
field_1 = [ x3 y3]
field_2 = [x1 y1]
field_3 = [x2 y2]
If they match, then the 1x1 name description will be added to re-build array so that i don't distrub the orginal matrix.
it would be a cleaner syntax using "swtich' than lots of "ifs" and "elseifs"!
[r c] = size(coors);
for i = 1:r
coor_xy = [coors(i,1) coors(i,2)];
switch coor_xy(1)
case coor_xy(1) == field_1(1) && coor_xy(2) == field_1(2)
name(i) = 'field_1';
case coor_xy(1) == field_2(1) && coor_xy(2) == field_2(2)
name(i) = 'field_2';
end
end
thanks guys

Answers (2)

Jos (10584)
Jos (10584) on 29 May 2019
I suggest you use ISMEMBER with the rows option, rather than if-else (or switch)
fieldlist = [x3 y3 ; x1 y1 ; x2 y2] ;
filedlist_names = {'field3', 'field1', 'field2'}
[tf, loc] = ismember(coor_xy, fieldlist, 'rows')
if tf
name = fieldlist_names{loc}
else
name = 'none'
end

shin hsu
shin hsu on 29 May 2019
thanks a lot, 'ismember' cover more incidents than i need for sure.

Categories

Find more on Tables 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!