How to stop data being overwritten in for loop?
23 views (last 30 days)
Show older comments
I have a project where I'm creating an app where users can create a spatial model of a building (no of floors, rooms, dimensions ect.). I don't understand how to have my data not be overwritten by every for loop (a loop i created to input data for each floor).
Any help would be greatly appreciated.
noOfFloors=input('Enter number of Floors:');
if noOfFloors <=0
disp('Enter valid number of floors');
return;
end
for i=1:1:noOfFloors
noOfRooms = input('Enter number of rooms on floor');
if noOfRloors <=0
disp('Enter valid number of rooms');
return;
end
x=zeros(1,noOfRooms);
y=zeros(1,noOfRooms);
height=zeros(1,noOfRooms);
width=zeros(1,noOfRooms);
length=zeros(1,noOfRooms);
area=zeros(1,noOfRooms);
volume=zeros(1,noOfRooms);
for j=1:1:noOfRooms
roomType=menu('Choose Space','Residential','Educational','Office','Storage','Toilet');
coordinates=inputdlg({'Enter x coordinates on this Floor','Enter y coordinates on this Floor'},'Data Input');
x(j)=str2double(coordinates{1});
y(j)=str2double(coordinates{2});
dimensions=inputdlg({'Enter width','Enter height','Enter length'},'Data Input');
width(j)=str2double(dimensions{1});
height(j)=str2double(dimensions{2});
length(j)=str2double(dimensions{3});
area(j)=width(j)*length(j);
volume(j)=width(j)*height(j)*length(j);
end
end
0 Comments
Accepted Answer
Stephen23
on 4 May 2022
Edited: Stephen23
on 4 May 2022
Use a structure array, which allows you different numbers of rooms on each storey. A simple example:
NmS = 5; % number of storeys
Out = repmat(struct(),1,NmS);
for ii = 1:NmS
NmR = 6; % number of rooms
x = nan(1,NmR);
y = nan(1,NmR);
for jj = 1:NmR
x(jj) = 3+jj+ii;
y(jj) = 4+jj+ii;
end
Out(ii).area = x.*y;
Out(ii).x = x;
Out(ii).y = y;
end
Here I hardcoded the values, but you get the idea... Lets have a look at the second storey:
Out(2).area
Out(2).x
Out(2).y
More Answers (1)
Torsten
on 3 May 2022
In the outer loop, by initializing all vectors to 0, you overwrite all the settings done in the inner loop.
Furthermore, I guess that you will have to initialize all variables as
zeros(noOfFloors,noOfRooms)
instead of
zeros(1,noOfRooms)
and - as stated - this must be done in front of the outer loop.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!