How do I make sure variables aren't overwritten in loops?

조회 수: 2 (최근 30일)
Jack Smillie
Jack Smillie 2019년 4월 20일
편집: Stephen23 2019년 4월 21일
I need to create a program that can document info on various floors which that can be later used to find out certain info on that floor such as plot a floor plan using coords or tell me how many rooms on whichever floor. However the variables keep getting overwritting the previous loops variables. This is the code I've got so far which is still a WIP for main features.
answerFloor=inputdlg('Enter','Number of Floors');
numberOfFloors=str2double(answerFloor{1});
if numberOfFloors<=0
disp('Invalid');
return
end
numberOfSpaces=zeros(1,numberOfFloors);
spaceX={1,numberOfSpaces};
spaceY={1,numberOfSpaces};
spaceZ={1,numberOfSpaces};
X={1,numberOfSpaces};
Y={1,numberOfSpaces};
for i=1:1:numberOfFloors
answerSpaces=inputdlg('Enter','Number of Spaces');
numberOfSpaces=str2double(answerSpaces{1});
for n=1:1:numberOfSpaces
list = {'Residential','Office','Education','Toilet','Storage'};
[indx,tf] = listdlg('ListString',list);
spaceType=[indx,tf];
answerSpaceX=inputdlg('Enter','Width of Space (m)');
answerSpaceY=inputdlg('Enter','Height of Space (m)');
answerSpaceZ=inputdlg('Enter','Depth of Space (m)');
spaceX(n)=str2double(answerSpaceX{1});
spaceY(n)=str2double(answerSpaceY{1});
spaceZ(n)=str2double(answerSpaceZ{1});
answerX=inputdlg('Enter','X Co-ordinate on floor (m)');
answerY=inputdlg('Enter','Y Co-ordinate on floor (m)');
X(n)=str2double(answerX{1});
Y(n)=str2double(answerY{1});
end
end

채택된 답변

Image Analyst
Image Analyst 2019년 4월 20일
I suggest you load up rows in a table. See documentation for the table() function.
  댓글 수: 3
Image Analyst
Image Analyst 2019년 4월 20일
Sure, if there will only be a few tables then you can add just a few lines at the beginning and end of your loop, just put it into a loop and do this in the loop
for k = 1 : numberOfFloors
if numberOfFloors > 1
clear(yourTable);
end
% Now do all your code to load up rows in yourTable.
% code......
% At the very end of the loop, you can split into separate tables:
if numberOfFloors == 1
table1 = yourTable;
elseif numberOfFloors == 2
table2 = yourTable;
end
end
Conversely you can have a single table and a column that specifies what floor you're on, and just deal with one table instead of multiple tables, and extract out ONLY the rows you need when you need them.
Stephen23
Stephen23 2019년 4월 21일
편집: Stephen23 2019년 4월 21일
"Is there a way to code it so that if I were to input 2 floors, it'll create 2 tables?"
Using one table would make processing your data easier, just add a column/variable that indicates the floor number. Then your code will trivially work for any number of floors.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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