How do I manipulate matrix elements conditionally without loops?
Show older comments
I have a practise problem that I'm really stuck with.
There is an input variable A that is a random
matrix with a random number of rows and columns. The element values of the matrix are random double precision numbers that fall in the range from
to
. The matrix has between 5 and
rows and between 5 and
columns. The operations must be solved with only vectorised code.
%given function parameters
function [B, C, D] = matrixFun(A)
%1) change matrix elements<0 to 999:
A(A<0)=999
%assign values to B
%2) replace positive elements with square root of element:
A(A>0)=sqrt(A)
%Assign values to C
%3) column vector from elements between -2 and 2:
a= A(-2 <= A <= 2)
D=sort(a)
end
How do I assign the changed values to the B and C matrices? And is there an alternative method than using A(A<0)? I can't find any relavent documentation.
2 Comments
Walter Roberson
on 16 Apr 2020
The problem with
A(A>0)=sqrt(A)
is that the left side selects only some of the locations in A, but the right side selects all of the locations in A. You should be selecting the same locations in A on both the right and the left.
By the way, after you change all the negative elements to 999, every element will be positive except for the entries that are 0, and the square root of 0 is 0 so you might as well just take the square root of everything.
Likewise, after you set all of the negatives to 999, none of the entries can be between -2 and 0.
Perhaps you are not intended to do the changes in that order?
a= A(-2 <= A <= 2)
As far as MATLAB is concerned, that means the same as
a= A(((-2 <= A) <= 2))
The first part, -2 <= A, results in an array of 0 (false) and 1 (true) values the same size as A. Then you compare that array of 0 and 1 entries <= 2, which would be true for all of them, because all 0 and 1 are less than 2.
Emily Stewart
on 16 Apr 2020
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!