How do I change my code to stop a for loop simply replacing rows of outputs in a uitable?
Show older comments
function drainage_system_design_rough
n=input('How many pipes are in the system? ');
PRef=[1:1:n];
for PRef=1:n
disp('Pipe reference:')
disp(PRef)
L=input('Pipe Length:');
schedule=input('Do you want to add pipe to drainage schedule? (Yes=1, No=0)?: ');
if schedule==1
col={'Pipe Length(m)'};
row={PRef};
dat={L};
uitable('columnname',col,'rowname',row,'data',dat);
end
end
I am really new to MATLAB but want to create a simple table to store drainage system information. I want the rows of the table to be labelled by the pipe references (the number of which depend on the number of pipes in the system). However, each time the for loop is executed only the information for the last pipe is stored in the table and it replaces the informaton for the previous pipe. If any could help me code this better so I had a table that added rows each time the for loop was executed but also stored the previous rows, that would be much appreciated.
Accepted Answer
More Answers (1)
Benjamin Kraus
on 4 Jun 2021
The code as it is currently written is creating a brand-new uitable every time the loop runs.
You need to update the code to either:
- Collect all the data, then create a uitable once with all the data.
- Create a uitable once at the beginning, then add data to the existing uitable.
Example of option 1:
ncols = 4;
nrows = 4;
colnames = cell(ncols,1);
rownames = cell(nrows,1);
data = cell(nrows,ncols);
for r = 1:nrows
for c = 1:ncols
rownames{r} = ['Row ' num2str(r)];
colnames{c} = ['Column ' num2str(c)];
data{r,c} = r*c;
end
end
uitable('ColumnName', colnames, 'RowName', rownames, 'Data', data)
Example of option 2:
tbl = uitable;
tbl.RowName = {};
tbl.ColumnName = {};
tbl.Data = {};
ncols = 4;
nrows = 4;
for r = 1:nrows
for c = 1:ncols
tbl.RowName{r} = ['Row ' num2str(r)];
tbl.ColumnName{c} = ['Column ' num2str(c)];
tbl.Data{r,c} = r*c;
end
end
The end result of both will be the same, but the first option is significantly more efficient.
1 Comment
Ed Paddock
on 7 Jun 2021
Categories
Find more on Develop Apps Programmatically 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!