Using a nested for loop to create a matrix that square roots positive integers and adds 30 to negative integers.
조회 수: 2 (최근 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!