Reputation: 430
I'm trying to write a function that puts the class, length, and value of each of the things in a cell array into a struct, but I keep getting an error with the switch statements
function [ out, common ] = IDcell( cA )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
cl={};
val={};
len={};
for x=1:length(cA)
switch cA(x)
case isnum
cl(x)='double';
case ischar
cl(x)='char';
case islogical
cl(x)='logical';
case iscell
cl(x)= 'cell';
end
val=[val cA{x}];
len=[len size(value(x))];
end
out=struct('value', val, 'class', cl, 'length', len);
end
[out]=IDcell(cA)
SWITCH expression must be a scalar or string constant.
Error in IDcell (line 8)
switch cA(x)
Upvotes: 2
Views: 12574
Reputation: 2778
isnum
is not a Matlab function. isnumeric
may be what you were thinking of, but it isn't what you typed. Which means your code is seeing case isnum
and it has no idea what the heck isnum
is, so it is telling you whatever it is, if you want to use it there you need to make it something that evaluates to a number (what it means by scalar) or to a piece of text (what it means by string constant).
Further, ischar
is a matlab function, but you are not using it the right way. You must use it as ischar(cA(x))
for example, will then evaluate to true
if cA(x)
is a string or snippet of text, will evaluate to false
if cA(x)
is anything else.
While it would be lovely if switch
worked this way, it doesn't. You can't put a thing in the switch
part, and then just list functions that need to be evaluated on that thing in the switch
part.
The kind of thing you can do is this:
switch class(x)
case 'double'
fprintf('Double\n');
case 'logical'
fprintf('Logical\n');
end
Here I have used the class
function the way it needs to be used, with an argument in it. And I then switch my cases based on the output of that function, class outputs a string.
Upvotes: 6