How can i generalize "if statement"

1 visualización (últimos 30 días)
연승 김
연승 김 el 22 de Mzo. de 2021
Comentada: 연승 김 el 23 de Mzo. de 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

Respuesta aceptada

Stephen23
Stephen23 el 22 de Mzo. de 2021
Editada: Stephen23 el 22 de Mzo. de 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 comentario
연승 김
연승 김 el 23 de Mzo. de 2021
Thank you!!! it works.
And I'll study about indexing in your links.
Thank you!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Graphics Object Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by