0

I am trying to run a loop over multiple files, by feeding the file names into a function. I have saved these file names as a structure using:

files=dir('testdata\*.siz');
nrows=size(files,1);

Now my loop is:

for i=1:nrows
filename=files.name{i};
Singapore(filename);
writetable(ans,'file.xls')
end

However, I get the error:
"Field reference for multiple structure elements that is followed by more reference blocks is an error."

I found that the error is in

filename=files.name{1};

but everywhere I've searched tells me to use { } to access fields in a structure. I also have tried other types of brackets in vain.

Additional Information:
'files' is the name of the structure
'name' is the first column field within 'files' containing the file names in inverted commas.

Joel Wong
  • 69
  • 9

1 Answers1

2

You are referencing the files struct wrong, you need:

files(i).name

The {} is for accessing cell arrays.

You should also use ii (or similar) instead of i as your indexing variable since i is a already Matlab variable (imaginary unit).

matlabgui
  • 5,642
  • 1
  • 12
  • 15
  • Got it! Thanks! So for the loop I did filename=files(i).name, and it worked – Joel Wong Sep 28 '15 at 13:28
  • I guess that it is not recommended to use `i` as a loop variable, but I have never got any troubles with that. The imaginary unit should be referenced via `1i` according to Matlabs recommendation. Further, in case the function is short the scope is small enough. I would say it is the same with Matlab as any language there. The larger the scope is the longer name of the variable. The only difference is that the scope of the loop variable in matlab ends when the function ends. – patrik Sep 28 '15 at 13:34
  • @JoelWong Consider accepting the answer if it helped ;) – Ander Biguri Sep 28 '15 at 13:40
  • @patrick - To be honest I have used i in the past and I never ran into problems either. I only mentioned it to be complete! :) – matlabgui Sep 28 '15 at 13:46
  • @patrik [this question](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) explains why you should not use `i` or `j` as variable names. It's both because you will get into trouble when using complex numbers and it is time consuming to overwrite a built-in function. – Adriaan Sep 28 '15 at 13:52
  • @Adriaan I do not disagree with that it is bad practice to use `i` and `j` as loop variables. However the overhead for this is minimal and the errors that can happen comes from already bad practice like not using `1i` and `1j` for imaginary unit. Further `1i` and `ii` does almost look the same, so I would rather recommend to use `k, n, m` in case short names are wanted. Apart from that, I prefer descriptive names like `fileI`. This is short, hard to mix up with something and gives a clear understanding about what the variable is supposed to represent. – patrik Sep 28 '15 at 14:01