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

### Jack Smillie (view profile)

on 20 Apr 2019
Latest activity Edited by Stephen Cobeldick

on 21 Apr 2019

### Image Analyst (view profile)

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.
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
for n=1:1:numberOfSpaces
list = {'Residential','Office','Education','Toilet','Storage'};
[indx,tf] = listdlg('ListString',list);
spaceType=[indx,tf];
end
end

### Image Analyst (view profile)

on 20 Apr 2019

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

Jack Smillie

### Jack Smillie (view profile)

on 20 Apr 2019
Is there a way to code it so that if I were to input 2 floors, it'll create 2 tables?
Image Analyst

### Image Analyst (view profile)

on 20 Apr 2019
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.
Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 21 Apr 2019
"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.