How to stop data being overwritten in for loop?

조회 수: 10 (최근 30일)
Tom Hughes
Tom Hughes 2022년 5월 3일
댓글: Tom Hughes 2022년 5월 4일
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

채택된 답변

Stephen23
Stephen23 2022년 5월 4일
편집: Stephen23 2022년 5월 4일
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
ans = 1×6
42 56 72 90 110 132
Out(2).x
ans = 1×6
6 7 8 9 10 11
Out(2).y
ans = 1×6
7 8 9 10 11 12

추가 답변 (1개)

Torsten
Torsten 2022년 5월 3일
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.
  댓글 수: 1
Tom Hughes
Tom Hughes 2022년 5월 4일
Thanks for your answer mate. However when I initialize variables as
zeros(noOfFloors,noOfRooms)
I get the error 'Size inputs must be scalar'.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by