Having trouble with looping through fields in a struct

3 views (last 30 days)
So I want to loop through a folder containing several .txt files. So, i start by choosing the folder where I want to work in and collect my files, here all files are formed as 21x2 double. Then I am trying to retrive data from the fields into seperate variabels, since when I collected them it was saved as a 8x1 struct, hence 8 fields(8 files of the size 21x2 double). And I want to end up with 2 variables of the form 21x1 double.
% Evaluation of mean bias for group
disp('Choose directory to work in');
path = uigetdir('');
list = dir(fullfile(path,'*.txt'));
data.t = zeros(length(list));
data.p = zeros(length(list));
for i = 1:length(list)
[data.t{i}, data.p{i}] = textread(list(i).name);
But, instead I get this error message
Unable to perform assignment because the left and right sides have a different number of elements.
Error in mean_bias (line 15)
[data.t(i), data.p(i)] =textread(list(i).name);
I am not sure of how to solve this, because when I earlier today wrote anoter pice of code in a similair way it worked without problem. only difference here is that in every file the first column is the same for every file I loop over and that is why I choose not to save those values in every iteration.
disp('Open BSIF input file');
[file path]=uigetfile([files.path '*.txt; *.crv; *.inp'],'Open input function file','MultiSelect','off');
files.inp=[path file];
list = dir(fullfile(path,'*.txt'));
for i = 1:length(list)-1
[t_tac, IDIF{i}] = textread(list(i+1).name);
a = IDIF{i}';
hold on
Anyone that could have an idea of how to solve this?
Amanda Eriksson
Amanda Eriksson on 2 Jun 2021
Oh thank you! I had tried so many types of way to save to new variables that I must have forgett to chaneg back to what I originally had!
It is now working, and I also removed the matrox definition, but I thought I already had tried that and it didn't work.. weird. But it works now! Thanks again :)

Sign in to comment.

Accepted Answer

Joseph Cheng
Joseph Cheng on 2 Jun 2021
Edited: Joseph Cheng on 2 Jun 2021
primarily its because of the
data.t = zeros(length(list));
data.p = zeros(length(list));
where you've set the t and p to be a matrix. but then when you are in the for loop you're trying to stuff the items into a existing matrix array index but trying to access it as a cell with probably a string. in your previous code you didn't pre-define what t and p were in the struct so matlab was able to correctly assign what it was.
Joseph Cheng
Joseph Cheng on 3 Jun 2021
It's generally a good idea. There is a way to preallocate for cells too but I forget. Mat2cell comes mind but unless you're dealing huge arrays or doing it many many times the overall efficiency isn't worth just ignoring the warning.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by