Filter löschen
Filter löschen

How can i generalize "if statement"

1 Ansicht (letzte 30 Tage)
연승 김
연승 김 am 22 Mär. 2021
Kommentiert: 연승 김 am 23 Mär. 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

Akzeptierte Antwort

Stephen23
Stephen23 am 22 Mär. 2021
Bearbeitet: Stephen23 am 22 Mär. 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 Kommentar
연승 김
연승 김 am 23 Mär. 2021
Thank you!!! it works.
And I'll study about indexing in your links.
Thank you!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by