Question

I want to check the length of string got more than 20 characters, if more than 20 then will return 1 else return 0 in matrix form [n x 1]. But now, I get the answer of [1x1]. How do I modify my code in if-else statement to get the ans?

str = {'http://www.mathworks.com/matlabcentral/newsreader/view_thread/324182',
  'http://jitkomut.lecturer.eng.chula.ac.th/matlab/text.html',
  'http://www.ee.ic.ac.uk/pcheung/teaching/ee2_signals/Introduction%20to%20Matlab2.pdf'};

a = cellfun(@length,str)

if a > 20
'1'
else
'0'
end

Output: a =

68
57
83


ans =

1

I want the output of, lets say

ans = 

1
1
1
Was it helpful?

Solution

In Matlab, you can simply use (no if statement is needed):

a = cellfun(@length,str)
(a>20)'

This will give you:

a =

   68   57   83

ans =

   1
   1
   1

OTHER TIPS

As @herohuyongtao mentions, you don't actually need an if, the if will only consider the first element of the matrix that it returns, hence giving you only a single value.

But you could actually do this all in your cellfun by using an anonymous function:

cellfun(@(x)(length(x) > 20), str)

And get the result in one shot.

As there is no equivalent of the c ternary operator (?:) in matlab, you can use the following two statements to replace your if then else statement, and achieve what you ask for:

b(a==a)='0'  
b(a>20)='1'

The first line initializes the result array, where all value b defaults to the value of the else branch, i.e. '0', the second line changes the elements for which the conditional > 20 holds to the value in the then branch, i.e. '1'.

If the output values are boolean, you can simply do:

(a>20)

as @herohuyongtao suggested or use @Dan's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top