MATLAB: How to replace the elements of a matrix using the conditions if,else

MATLABmatrix manipulation

I want to replace the elements of a matrix
using different conditions. For instance, let all
elements larger than 0.5 be replaced by -1, else
keep the way it is.
So I thought I should simply write the command below:
X=rand(10,10);
if X(:,:)>0.5;
T(:,:)=-1;
else T=X(:,:);
end;
but it does not work because T==X.
Could someone tell me how to correct these command lines?
Thank you
Emerson

Best Answer

IF statements do not pick out elements of an array like you are imagining that they do. When you write this:
if conditional
% Do something
end
for non-scalar conditional, the IF statement will pass if and only if all of the elements in conditional are true or non-zero. For example:
x = [1 2 3]; % All are non-zero, passes conditional...
if x
disp('In if')
end
but now change it to:
x = [1 2 0]; % All are not non-zero, fails conditional...
if x
disp('In if')
end
So the way you have to do what you want is either through logical indexing, or by single value through iteration.
% iteration approach - look at one value at a time!
x = [.1 .2 .3 .7 .8 .9 .1 .2 .3]; % Work with this array.

T = zeros(size(x)); % Make another array to fill up...
for ii = 1:length(x)
if x(ii)>.5
T(ii) = 99;
else
T(ii) = -100;
end
end
% Logical indexing approach
x = [.1 .2 .3 .7 .8 .9 .1 .2 .3]; % Work with this array.
T(x>.5) = 99;
T(x<=.5) = -100