Need help with a loop and storing inputs in arrays

I am trying to create a program that asks you how many floors are in a building, the how many rooms are on each floor and then proceeds to ask questions about each room to receiev information on height, width etc. I have managed to get it work if the buiding isonly one floor however when it becomes more thanthis it seems to overwrite the data inputted for the first floor. Any help would be appreciated.
numberOfFloors=input('Enter the number of floors in this building:');
if numberOfFloors<1
message1=msgbox (['At least 1 floor must be created']);
else
numberOfSpacesOnEachFloor=zeros(1,numberOfFloors);
end
for i=1:1:numberOfFloors
numberOfSpacesOnEachFloor(i)=input('Please Enter the Number of Spaces on this Floor:');
if numberOfSpacesOnEachFloor<1
message2=msgbox (['At least 1 space must be created on this floor']);
else
end
end
space=1;
residential=0;
office=0;
education=0;
toilet=0;
storage=0;
for i=1:1:numberOfFloors
for i=1:1:numberOfSpacesOnEachFloor(space)
widths(i)=input('Please enter the width of this space:');
heights(i)=input('Please enter the height of this space:');
depths(i)=input('Please enter the depth of this space:');
residentialRoom=questdlg('Is this space residential?', 'Residential?','Yes','No','No');
switch residentialRoom
case 'Yes'
residential=residential+1;
otherwise
officeRoom=questdlg('Is this space an office?', 'Office?','Yes','No','No');
switch officeRoom
case 'Yes'
office=office+1;
otherwise
educationRoom=questdlg('Is this space a educational?', 'Education?','Yes','No','No');
switch educationRoom
case 'Yes'
education=education+1;
otherwise
toiletRoom=questdlg('Is this space a toilet?', 'Toilet?','Yes','No','No');
switch toiletRoom
case 'Yes'
toilet=toilet+1;
otherwise
storage=storage+1;
end
end
end
end
x(i)=input('Please enter the x co-ordinate of the bottom left corner of this space');
y(i)=input('Please enter the y co-ordinate of the bottom left corner of this space');
end
space=space+1;
end
disp(['Number of residential rooms: ',num2str(residential)]);
disp(['Number of offices: ',num2str(office)]);
disp(['Number of educational rooms: ',num2str(education)]);
disp(['Number of toilets: ',num2str(toilet)]);
disp(['Number of storage rooms: ',num2str(storage)]);

Answers (1)

for i=1:1:numberOfFloors
for i=1:1:numberOfSpacesOnEachFloor(space)
These are two loops with the same counter. Use two different counters and create matrices instead:
x(i)
for i1 = 1:numberOfFloors
for i2 = 1:numberOfSpacesOnEachFloor(space)
x(i1, i2) = ...
end
end
If the number of elements are different, use a cell array instead:
x{i1}(i2) = ...

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 20 May 2021

Answered:

Jan
on 20 May 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!