Info
此问题已关闭。 请重新打开它进行编辑或回答。
How do I avoid using a lot of if statements in a row?
1 次查看(过去 30 天)
显示 更早的评论
Hi all! I have to execute the content of the following code, which I'm sure can be written in a much more elegant and efficient way. The meaning is clear: for each of the 11 events I'm interested in, if the matrix dffx that corresponds to that event is empty, then it becomes [dffx,num_dff]; otherwise, it becomes [dff1;num_dff]. I am sure that such a trivial work can be executed in way less lines of code. Can you help? Thank you!
if code_events(i) == 1
if isempty(dff1)
dff1=[dff1,num_dff];
else
dff1=[dff1;num_dff];
end
elseif code_events(i) == 2
if isempty(dff2)
dff2=[dff2,num_dff];
else
dff2=[dff2;num_dff];
end
elseif code_events(i) == 3
if isempty(dff3)
dff3=[dff3,num_dff];
else
dff3=[dff3;num_dff];
end
elseif code_events(i) == 4
if isempty(dff4)
dff4=[dff4,num_dff];
else
dff4=[dff4;num_dff];
end
elseif code_events(i) == 5
if isempty(dff5)
dff5=[dff5,num_dff];
else
dff5=[dff5;num_dff];
end
elseif code_events(i) == 6
if isempty(dff6)
dff6=[dff6,num_dff];
else
dff6=[dff6;num_dff];
end
elseif code_events(i) == 7
if isempty(dff7)
dff7=[dff7,num_dff];
else
dff7=[dff7;num_dff];
end
elseif code_events(i) == 8
if isempty(dff8)
dff8=[dff8,num_dff];
else
dff8=[dff8;num_dff];
end
elseif code_events(i) == 9
if isempty(dff9)
dff9=[dff9,num_dff];
else
dff9=[dff9;num_dff];
end
elseif code_events(i) == 10
if isempty(dff10)
dff10=[dff10,num_dff];
else
dff10=[dff10;num_dff];
end
elseif code_events(i) == 11
isempty(dff11)
dff11=[dff11,num_dff];
else
dff11=[dff11;num_dff];
end
end
end
5 个评论
Stephen23
2020-4-1
C = {dff1,dff2,...};
for k = 1:numel(C)
C{k} = [C{k};num_dff];
end
Using numbered variables is usually a sign that your code will be complex and/or inefficient.
回答(2 个)
Star Strider
2020-4-1
Another option is switch,case,otherwise. You will need to determine if that is an improvement over the multiple if blocks.
0 个评论
Steven Lord
2020-4-1
Do you need to have eleven individually numbered variables, or are they all the same size and type (and therefore "stackable" as rows / columns / pages / etc. of a larger array)?
x1 = [ 1; 2; 3; 4];
x2 = [ 5; 6; 7; 8];
x3 = [ 9; 10; 11; 12];
x4 = [13; 14; 15; 16];
x = reshape(1:16, [4 4]); % [x1; x2; x3; x4]
With those examples, it would be much easier to iterate over the columns of x than the individual variables x1, x2, x3, and x4.
If they're not all the same size or not all the same type, consider a cell array.
1 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!