Is there is a faster way doing this? (I am currently using 100 "if/elseif" statements in a row...)

6 次查看(过去 30 天)
So I have created a popupmenu which asks the user to define the size of a matrix (number of columns and number of rows). They can select numbers 2-10 for each.
Currently what I am doing is the following:
function pushbutton_Callback(~, ~, columns, rows)
%Get the number of columns
contents = get(columns,'String');
c = str2num(contents{get(columns,'Value')});
%get the number of rows
contents = get(rows,'String');
r = str2num(contents{get(rows,'Value')});
%display the data
A = [c r];
if A==[2 2]
elseif A==[2 3]
elseif A==[2 4]
.
.
.
elseif A==[10 10]
end
Each "if"/"elseif" statement has it's own code which generate the matrix (but I'm not including it here because that isn't important).
Is there are more "efficient" way of doing this? This was the first solution I thought of, but I'm beginning to think there MUST be an easier way of doing this... How might I be able to do the same thing as what I'm trying to do, but without using 100 separate "if" statements?
  1 个评论
Stephen23
Stephen23 2016-2-9
Although you write that " I'm not including it here because that isn't important", writing a generalized matrix generator would remove the need for this ugly if (or switch) chain entirely.
Can your matrix creation be generalized? How is each matrix specified?

请先登录,再进行评论。

回答(2 个)

Walter Roberson
Walter Roberson 2016-2-8
Using switch and case could make it syntactically more pleasant.
You could create 10 x 10 cell array of function handles, one for each different action, and index that cell array to determine which function to execute.
Are you sure that the code to create the matrix cannot be generalized to use variables to determine limits?

iker azpeitia
iker azpeitia 2016-2-9
Your if/elseif proposal is not viable. As Walter Roberson suggests, I think you should use two for statements, one inside the other.
for (col=1:c)
for (row=1:r)
m(row,col)=2; %%or the value you want.
end
end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by