switch case - choose from array

7 ビュー (過去 30 日間)
yaniv friedman
yaniv friedman 2017 年 1 月 18 日
回答済み: Stephen23 2017 年 1 月 18 日
I'm trying to run a function which includes this part:
optionsVec = [1 5 12 14];
for k=1:10
switch k
case num2cell(optionsVec)
disp('k is an option')
otherwise
disp('k is not an option')
end
end
But the num2cell function is very time consuming.
How can I preform the same action - compare k to numbers within an array - more efficiently?
Thanks!

採用された回答

Stephen23
Stephen23 2017 年 1 月 18 日
Do the conversion before the loop:
C = num2cell(optionsVec);
for ...
switch ...
case C
...
end
end

その他の回答 (1 件)

Adam
Adam 2017 年 1 月 18 日
validIdx = ismember( 1:10, [1 5 12 14] );
for n = 1:numel( validIdx )
if validIdx(n)
disp( 'k is an option' )
else
disp( 'k is not an option' )
end
end
should achieve the same thing, printing one or other of those statements 10 times. There may be a neater way than the for loop to do the disp part too, but there is certainly no need for cell arrays.

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by