Solving Boolean Vector: Position of "1" Values

  • Thread starter Thread starter phillyj
  • Start date Start date
  • Tags Tags
    Confused Loop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
phillyj
Messages
30
Reaction score
0
Hi, I needed to write a function that takes a boolean vector and returns the position of the "1" values only. The correct way it was done was like this :
Code:
function res = tmp(x)
res=[ ];
for k=1:length(x)
if x(k) 
    res = [res,k];
end
end

I don't understand why the "if" statement returns only the value "1"? I thought that I might have to make a boolean statement that checks if the value at "k" is equal to "1" like this "if x(k) ==1"

Please help, it's very confusing to me
 
Physics news on Phys.org
the function you are trying to write is a MATLAB function already. Try
Code:
find(x)
or read the documentation from
Code:
doc find
 
trambolin said:
the function you are trying to write is a MATLAB function already. Try
Code:
find(x)
or read the documentation from
Code:
doc find

You misunderstand me. I know this is a built-in fuction but this was an exercise in learning MATLAB conditionals. Can you explain my original question on why the output works that way? My professor isn't around this week otherwise I might ask him.

Thanks
 
actually your code works fine
I did this
Code:
x = [true false true]
res = [];
for k=1:length(x)
if x(k)
res = [res,k];
end
end
and the result is res = [1,3]
 
trambolin said:
actually your code works fine
I did this
Code:
x = [true false true]
res = [];
for k=1:length(x)
if x(k)
res = [res,k];
end
end
and the result is res = [1,3]

Yes, the code works. I want to know why the if statement returns only the true values. I'm still learning. When I read the code in my mind this is what I understand: From index 1 to the end of the vector, result is index. Isn't that what
Code:
if x(k)
means? This makes no sense to me. Conditionals confuse me so much. Why aren't the false elements outputted. How does MATLAB differentiate between the true and false in this statement?
 
"if x(k)" evaluates to true when x(k) is 1 (and possibly any other nonzero value), and evaluates to false when x(k) is 0.

This code could be written more clearly as

Code:
if x(k) == 1
  res = [res, k];
end
 
Ah, now I got it. It works because you should read the if clause as follows

Code:
if (value that is declared here is nonzero)
...
end

For example
Code:
if 5
...
end
always executes but

Code:
if 0
...
end
never executes. See "doc if" in Matlab for details.