MATLAB: Converting a string to class Logical?

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 7K views
btbam91
Messages
91
Reaction score
0
Hey guys.

So this problem asks me write a function that accepts a string, and outputs an array of class logical where the true values are the vowels and everything is false.

As of now, I have:

function array = arraylogical(c)
%Purpose: This function accepts a string, c, and returns a logical array in
%which vowels are true and consonants are false.

%Find length of c
n = length(c);

%Initiate for loop
for ii = 1:n
if c(ii) == 'A'
c(ii) = '1';
elseif c(ii) == 'E'
c(ii) = '1';
elseif c(ii) == 'I'
c(ii) = '1';
elseif c(ii) == 'O'
c(ii) = '1';
elseif c(ii) == 'U'
c(ii) = '1';
elseif c(ii) == 'a'
c(ii) = '1';
elseif c(ii) == 'e'
c(ii) = '1';
elseif c(ii) == 'i'
c(ii) = '1';
elseif c(ii) == 'o'
c(ii) = '1';
elseif c(ii) == 'u'
c(ii) = '1';
else
c(ii) = '0';
end%if
end%for
end%function

And when I run this function for say the string 'AAA' I get 111(The problem with this is that it's a 1x1 array of 111, I need a 1x3 array) as an output, when I'm trying to get a logical array of 1 1 1.Thanks for the guidance.
 
Physics news on Phys.org
All you are doing is replacing one character in your input array with another. E.g., when c(ii) == 'A', you are setting c(ii) to '1', which is a character value. Instead, assign the value 1 for true and 0 for false, not the characters '1' and '0'.

Also, it's probably better to return a different array than to overwrite the values in your input array.