How do I use inputdlg in a for loop to return a numerical array?
3 次查看(过去 30 天)
显示 更早的评论
I need to make a program that asks the user how many floors there are and then input each floors dimensions in sequence and then store them in a numerical array for use later but I'm very new to this and struggling somewhat! The contentws of the for loop work fine outside the loop.
floors=inputdlg('enter number of floors: ');
for i=1:1:floors
dimensions={'Enter height','Enter width:','Enter length:'};
dlgtitle='Dimensions';
dims=[1 35];
answer=inputdlg(dimensions,dlgtitle,dims);
height(i)=str2num(answer{1});
width(i)=str2num(answer{2});
length(i)=str2num(answer{3});
end
2 个评论
Rik
2020-4-10
I'm on mobile so I can't test your code, but I already see a potential source of issues: you're shadowing the internal function length() with a variable. You are also using str2num instead of the recommended str2double (which avoids an internal call to eval() with all the potential side effects).
采纳的回答
Rik
2020-4-11
A few good practice tips:
- avoid i and j as variable names to avoid confusion with sqrt(-1), avoid l (lowercase L) as well to avoid confusion with the numeral 1.
- put all code that does not depend on your loop index outside of your loop so it is executed only once
- don't use variable name like sum or length, as that will prevent you from using the internal functions with that name (this is called 'shadowing' of a function)
- pay attention to the warnings mlint is giving you, try to resolve all warnings. If you are certain the warning doesn't apply in your case (which is rare), right-click the orange line and select the 'suppress warning on this line' option.
So here is your code with those tips applied:
n_floors=inputdlg('enter number of floors: ');
n_floors=str2double(n_floors);
dimensions={'Enter height','Enter width:','Enter length:'};
dlgtitle='Dimensions';
dims=[1 35];
height=zeros(1,n_floors);
width=zeros(1,n_floors);
len=zeros(1,n_floors);%you could consider depth as a variable name
for floor=1:n_floors
answer=inputdlg(dimensions,dlgtitle,dims);
height(floor)=str2double(answer{1});
width(floor)=str2double(answer{2});
len(floor)=str2double(answer{3});
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!