Azzera filtri
Azzera filtri

How can i generalize "if statement"

1 visualizzazione (ultimi 30 giorni)
연승 김
연승 김 il 22 Mar 2021
Commentato: 연승 김 il 23 Mar 2021
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

Risposta accettata

Stephen23
Stephen23 il 22 Mar 2021
Modificato: Stephen23 il 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:
  1 Commento
연승 김
연승 김 il 23 Mar 2021
Thank you!!! it works.
And I'll study about indexing in your links.
Thank you!!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Graphics Object Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by