MATLAB Answers

0

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

Asked by Jack Smillie on 20 Apr 2019
Latest activity Edited by Stephen Cobeldick on 21 Apr 2019
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

  0 Comments

Sign in to comment.

1 Answer

Answer by Image Analyst
on 20 Apr 2019
 Accepted Answer

I suggest you load up rows in a table. See documentation for the table() function.

  3 Comments

Is there a way to code it so that if I were to input 2 floors, it'll create 2 tables?
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.
"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.

Sign in to comment.