p=[-1.0000 1.0000 -1.0000 -1.0000 -1.0000 -1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 -1.0000 ];
k=1;
i=0;
D=[];
for i=1:length(p)
a=p(i);
if a==-1.0000
D(1,k)=0;
else
D(1,k)=1;
end
k=k+1;
end
D
At first glance it should work as you asked, but it depends on how you
obtained the numbers in p. If you had round off errors arriving at the minus
ones, they might not be exactly minus ones and then the loop wouldn't work.
However, it's a awkward way to do the job in any case. You could simply
write:
D = zeros(1,length(p));
D(p>0) = 1;
Roger Stafford
In the interest of brevity you could also use the one-liner:
D = +(p>0);
Roger Stafford
D = p>0
Because
all(p>0==+(p>0))
ans =
1
Or was it just stylistic?
I assumed Omar would like to have a numeric type result rather than logical.
(On my own version 4a it makes no difference. It never heard of logical
types.)
Roger Stafford
Thanks Roger, I had never seen that conversion before. I
have found that sometimes it is confusing as to when Matlab
enforces the "This is a logical variable, you cannot use it
as a double" (or the opposite)rule. For example:
p=[-1.0000 1.0000 -1.0000 -1.0000 -1.0000 -1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 -1.0000 ];
p1 = p>0; % logical
p2 = +(p>0); % numeric
% Yet Matlab has no problem with the following:
p1+2.4
% Nor this
p2+true(size(p2))
So the types mix easily and intuitively.
You do have to be careful in certain cases. For example, suppose p =
[5,10]. Then
p(p>0)
produces [5,10] whereas
p(+(p>0))
gives [5,5] as a result.
I guess one lesson here is don't rely on "==" completely for distinguishing
different types.
Roger Stafford