MATLAB: How to create an output of matrices using if statements
if statementmultiple input/output
Suppose i have x = rand(1,100); and i want to compute an array of values of y, if output of random x is less than 0.2, y = 3; or else, y = 4.
how do i write the code so that i have a matrices of y?
Best Answer
x = rand(1,100);
y = repmat(3, size(x)); % Set all to 3
y(x >= 0.2) = 4; % Set matching elements to 4
Or in 2 steps:
y = zeros(size(x));
match = (x < 0.2);
y(match) = 3;
y(~match) = 4;
The "if-statement" is hidden inside the logical indexing operation "x < 0.2". With a loop and a real if-statement (which is less efficient):
y = zeros(size(x));
for k = 1:numel(x)
if x(k) < 0.2
y(k) = 3;
else
y(k) = 4;
end
end
The "vectorized" methods above are faster andnicer. The latter means, that they are easier to read and offer less chances for typos and therefore reduce the time required for debugging.
Best Answer