Having trouble with looping through fields in a struct
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Amanda Eriksson
il 2 Giu 2021
Commentato: Joseph Cheng
il 3 Giu 2021
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
files.path='';
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);
end
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.
files.path='';
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
plot(t_tac*60,a)
end
Anyone that could have an idea of how to solve this?
2 Commenti
Risposta accettata
Joseph Cheng
il 2 Giu 2021
Modificato: Joseph Cheng
il 2 Giu 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.
2 Commenti
Joseph Cheng
il 3 Giu 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Cell Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!