Attempt to reference field of non-structure array. Error while trying to read txt file

Here's my code:
%read
fid = fopen('data.txt','r');
while 1 == 1
[A, COUNT] = fscanf(fid, '%s');
for i = 1:A.length();
disp(i);
end
end
I keep getting the error, "Attempt to reference field of non-structure array."
On line 5, :for i = 1:A.length();
why is this?

Answers (1)

"why is this?"
Because this is not MATLAB code:
A.length()
Structures have fields, but A is not a structure.
According to its documentation the function sscanf will output any of "column vector | matrix | string | character array", but none of those data types have methods or fields, so that code will never work. Try using the function form instead (as is standard in MATLAB, and as is also shown clearly in the length documentation):
length(A)
Although even better would be to use numel, which is probably what you meant to use:
numel(A)
Although beginners and computer programmers seem to despise looking at the documentation, it really is rather useful for knowing how MATLAB works and how functions should be used. There are even working examples!

3 Comments

Let me try that, sorry, new to matlab, and it can be confusing for someone who has used other languages, cause it is different in a lot of ways.
But while 1==1 will give an infinite loop which will only exit when it hits an error - not elegant or robust programming to say the least.

Sign in to comment.

Categories

Tags

Asked:

on 10 Jul 2015

Edited:

on 12 Jul 2015

Community Treasure Hunt

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

Start Hunting!