requirement Switch & Case expression with matrix

7 ビュー (過去 30 日間)
shin hsu
shin hsu 2019 年 5 月 29 日
回答済み: shin hsu 2019 年 5 月 29 日
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

回答 (2 件)

Jos (10584)
Jos (10584) 2019 年 5 月 29 日
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 2019 年 5 月 29 日
thanks a lot, 'ismember' cover more incidents than i need for sure.

カテゴリ

Help Center および File ExchangeTables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by