requirement Switch & Case expression with matrix

조회 수: 9 (최근 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 CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by