How to stop data being overwritten in for loop?
조회 수: 10 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
Out(2).x
Out(2).y
추가 답변 (1개)
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!