Attempt to reference field of non-structure array. Error while trying to read txt file
Show older comments
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)
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
Geoffrey Moody
on 10 Jul 2015
Edited: Geoffrey Moody
on 10 Jul 2015
Geoffrey Moody
on 10 Jul 2015
Image Analyst
on 10 Jul 2015
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.
Categories
Find more on Characters and Strings 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!