How can i generalize "if statement"

1 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2021-3-22
编辑:Stephen23 2021-3-22
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 个评论
연승 김
연승 김 2021-3-23
Thank you!!! it works.
And I'll study about indexing in your links.
Thank you!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by