Using a nested for loop to create a matrix that square roots positive integers and adds 30 to negative integers.

조회 수: 7(최근 30일)
for X=[4,-5,13;19,-13,21;-33,77,144]
for X>=0
Y=sqrt(X)
for X<0
Y=X+30
end
end
end
I am trying to use a nested for loop to calculates the matrix Y by calculating the square roots of all the
elements of X which are greater than or equal to 0. And for elements of X that are negative
add 30 to the elements.
The script should work for a matrix of any size.

답변(1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2022년 10월 30일
편집: KALYAN ACHARJYA 2022년 10월 30일
X=[4,-5,13;19,-13,21;-33,77,144]
X = 3×3
4 -5 13 19 -13 21 -33 77 144
[r,c]=size(X);
Y=zeros(length(X));
for i=1:r
for j=1:c
if X(i,j)>=0
Y(i,j)=sqrt(X(i,j));
else
Y(i,j)=X(i,j)+30;
end
end
end
Y
Y = 3×3
2.0000 25.0000 3.6056 4.3589 17.0000 4.5826 -3.0000 8.7750 12.0000
% Suggested & Efficient way
%Efficint Way
%Z=double(X<0).*30+X;
Try the other condition at your own, One way multiply & change X condition
#More:
%Efficint Way: You can make it more simpler or 1 line code
Z1=double(X<0).*X+30*double(X<0);
Z2=sqrt(double(X>=0).*X);
Y=Z1+Z2
Y = 3×3
2.0000 25.0000 3.6056 4.3589 17.0000 4.5826 -3.0000 8.7750 12.0000

범주

Find more on Loops and Conditional Statements 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!

Translated by