MATLAB: Converting a string to class Logical?

Click For Summary
The discussion focuses on creating a MATLAB function that converts a string into a logical array, where vowels are represented as true (1) and consonants as false (0). The initial implementation incorrectly replaces characters in the input string with '1' and '0', resulting in a character array instead of a logical array. It is suggested to use numeric values for true and false instead of character representations. Additionally, it is recommended to create a new output array rather than modifying the input string directly. The goal is to achieve a logical array that accurately reflects the presence of vowels in the input string.
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.
 
Got it, thanks!
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
3K
Replies
43
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
2
Views
2K
Replies
2
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
690
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 15 ·
Replies
15
Views
2K