Home > Archive > Matlab > October 2006 > switch with cell arrays
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
switch with cell arrays
|
|
| aktaepe 2006-10-12, 7:14 pm |
| I want to use a switch statement with a cell array as case_expr. This
poses no problem when the cell array has few elements, eg:
switch number
case {'1', '2'}
disp('number <=2')
case {'3', '4'}
disp('number >=3')
However, this is impractical for large cell arrays, as in {'1', '2',
...., '99', '100'}.
Does anyone know of an efficient way to generate such cell arrays?
Thanks.
| |
| Titus Edelhofer 2006-10-12, 7:14 pm |
| Hi,
help mat2cell
although I would probably prefer some if-elseif-construct here, esp. if
the ranges get larger:
if number<=2
disp('number <=2')
elseif number<=4
disp('number >=3')
end
Titus
"aktaepe" <aktaepe@gmail.com> schrieb im Newsbeitrag
news:ef43555.-1@webcrossing.raydaftYaTP...
>I want to use a switch statement with a cell array as case_expr. This
> poses no problem when the cell array has few elements, eg:
> switch number
> case {'1', '2'}
> disp('number <=2')
> case {'3', '4'}
> disp('number >=3')
>
> However, this is impractical for large cell arrays, as in {'1', '2',
> ..., '99', '100'}.
>
> Does anyone know of an efficient way to generate such cell arrays?
>
> Thanks.
| |
| aktaepe 2006-10-12, 7:14 pm |
| Danke viel Mal, for the mat2cell tip.
agreed, in general, an if-elseif would be more suitable. In this
particular case, and mostly for historical reasons, I prefer the
switch option.
Titus Edelhofer wrote:
>
>
> Hi,
>
> help mat2cell
>
> although I would probably prefer some if-elseif-construct here,
> esp. if
> the ranges get larger:
>
> if number<=2
> disp('number <=2')
> elseif number<=4
> disp('number >=3')
> end
>
> Titus
>
> "aktaepe" <aktaepe@gmail.com> schrieb im Newsbeitrag
> news:ef43555.-1@webcrossing.raydaftYaTP...
> This
> '2',
> arrays?
>
>
>
| |
| badams 2006-10-31, 7:10 pm |
| There is a way without the if statement. First you need to create an
array (the size you want)and convert each element to a string:
A = cell(1,100);
for n=1:100
A{n}=num2str(n);
end
Then use the whole array as your case_expr:
switch number
case {'test'}
disp('test')
case A
disp('a number between 1 and 100')
end
aktaepe wrote:[color=darkred]
>
>
> Danke viel Mal, for the mat2cell tip.
>
> agreed, in general, an if-elseif would be more suitable. In this
> particular case, and mostly for historical reasons, I prefer the
> switch option.
>
> Titus Edelhofer wrote:
> case_expr.
> {'1',
| |
| badams 2006-10-31, 7:10 pm |
| Sorry, this is more like it.
A = cell(1,100);
for n=1:100
A{n}=num2str(n);
end
switch number
case test
disp('test');
case A
disp('a number between 1 and 100');
end
|
|
|
|
|