Using a nested for loop to create a matrix that square roots positive integers and adds 30 to negative integers.
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
KALYAN ACHARJYA
le 30 Oct 2022
Modifié(e) : KALYAN ACHARJYA
le 30 Oct 2022
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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!