How can i generalize "if statement"
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi. everyone ~!
Thank you for reading^^
I'm a beginner to MATLAB, so please help me..!
I want to generalize "if statement" below for enlarging the size of instance.
In this code, I have described four variables(x(1), x(2), x(3), x(4)) in consideration of all possibilities.
I know that the way I code is very stupid...
how i can generalize in n variables...??
if (x(1)==1)&&(x(2)==1)&&(x(3)==1)&&(x(4)==1)
edges = edges;
elseif (x(1)==1)&&(x(2)==1)&&(x(3)==1)
edges = edges([1 2 3],:);
elseif (x(1)==1)&&(x(2)==1)&&(x(4)==1)
edges = edges([1 2 4],:);
elseif (x(1)==1)&&(x(3)==1)&&(x(4)==1)
edges = edges([1 3 4],:);
elseif (x(2)==1)&&(x(3)==1)&&(x(4)==1)
edges = edges([2 3 4],:);
elseif (x(1)==1)&&(x(2)==1)
edges = edges([1 2],:);
elseif (x(1)==1)&&(x(3)==1)
edges = edges([1 3],:);
elseif (x(1)==1)&&(x(4)==1)
edges = edges([1 4],:);
elseif (x(2)==1)&&(x(3)==1)
edges = edges([2 3],:);
elseif (x(2)==1)&&(x(4)==1)
edges = edges([2 4],:);
elseif (x(3)==1)&&(x(4)==1)
edges = edges([3 4],:);
elseif (x(1)==1)
edges = edges(1,:);
elseif (x(2)==1)
edges = edges(2,:);
elseif (x(3)==1)
edges = edges(3,:);
elseif (x(4)==1)
edges = edges(4,:);
else
edges = [1 1 ; 2 2];
end
0 commentaires
Réponse acceptée
Stephen23
le 22 Mar 2021
Modifié(e) : Stephen23
le 22 Mar 2021
Assuming that x is a four-element numeric vector or logical vector, something like this should work:
if any(x)
edges = edges(x==1,:);
else
edges = [1,1;2,2];
end
You need to learn how to use logical indexing, which is a simple and powerful way to access data in arrays:
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!