requirement Switch & Case expression with matrix
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (2)
Jos (10584)
le 29 Mai 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
0 commentaires
Voir également
Catégories
En savoir plus sur NaNs dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!