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

13 ビュー (過去 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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by