Using a nested for loop to create a matrix that square roots positive integers and adds 30 to negative integers.
1 次查看(过去 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.
0 个评论
回答(1 个)
KALYAN ACHARJYA
2022-10-30
编辑:KALYAN ACHARJYA
2022-10-30
X=[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
% 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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!