필터 지우기
필터 지우기

multiple switch-case, get position value

조회 수: 1 (최근 30일)
Elysi Cochin
Elysi Cochin 2017년 10월 3일
댓글: Walter Roberson 2017년 10월 3일
switch var
case {'ABC' 'ADE' 'AFG' 'AHI'}
Str = 'A';
case {'BAC' 'BDE' 'BFG' 'BHI'}
Str = 'B';
end
The above is my switch-case condition. Is there a way if i select
"ADE" The Str should be "A", and the pos should 2.
"BHI" The Str should be "B", and the pos should 4.
Is there a way i can do to get the position, or should i write switch-case again

채택된 답변

Guillaume
Guillaume 2017년 10월 3일
switch ... case (or if ... elseif ...) statements are simple to understand and are great for beginners, but are very limited. To do what you want with a switch you'd have to split each of your case statement into 4, so you'd have
switch var
case 'ABC'
Str = 'A'; pos = 1;
case 'ADE'
Str = 'A'; pos = 2;
...etc
A much simpler way to do what you want is not to use switch at all, and just use look-up tables:
lookuptable = {{'ABC' 'ADE' 'AFG' 'AHI'}, 'A';
{'BAC' 'BDE' 'BFG' 'BHI'}, 'B'};
for row = 1:size(lookuptable, 1)
[found, pos] = ismember(var, lookuptable{row, 1});
if found
Str = lookuptable{row, 2};
break;
end
end
if found
fprintf('"%s" found, Str is "%s" and pos is %d\n', var, Str, pos);
else
fprintf('"%s" not found\n', var);
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 10월 3일
[tf, idx] = ismember(Str, lookuptable(:,2));
if tf
var = lookuptable{idx,1}{pos};
else
var = '';
end

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

KSSV
KSSV 2017년 10월 3일
str = {'ABC' 'ADE' 'AFG' 'AHI'} ;
pos = 1:length(str) ;
idx = pos(strcmp(str,'ADE'))
  댓글 수: 1
Guillaume
Guillaume 2017년 10월 3일
ismember is simplet for that:
[found, pos] = ismember('ADE', str)

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2017년 10월 3일
Provided that you can sort the cases by initial letter and all the entries with the same initial letter are to be considered together,
cases = {'ABC' 'ADE' 'AFG' 'AHI', 'BAC' 'BDE' 'BFG' 'BHI'};
[vars, startpos, uidx] = unique( cellfun( @(V) V(1), cases ), 'stable');
Then,
[tf, idx] = ismember(var, cases);
if tf
groupidx = uidx(idx);
Str = vars(groupidx);
pos = idx - startpos(groupidx) + 1;
else
Str = ''; pos = [];
end

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by