Reputation: 127
Declaring a variable (filename
) in line 2 and using it in line 4 gives error.
If I give use data.temp(12,;)
then it runs fine but if i give filename = temp
and index = 12
as an input and then run data.filename(index,:);
,it gives an error. Somebody please help me out here
Here is the exact code:
data = importdata('check.mat');
filename = input('Enter the filename: ','s');
index = input('Enter Index of the file: ');
row = data.filename(index,:);
Reference to non-existent field 'filename'
Upvotes: 1
Views: 45
Reputation: 8401
As an alternative to getfield
, you can also use dynamic field names that, in the recent versions of Matlab I've used, permit direct indexing of the referenced field:
stuff = data.(filename)(index,:);
The sub-expression data.(filename)
resolves to the data in the field filename
of the data
struct and (index,:)
then indexes that data.
Upvotes: 1
Reputation: 35525
You are using structs wrongly.
When accessing a structure using a string, you need to use getfield
, because fieldname
contains a string, but when you do data.fieldname
you are not actually using the value of fieldname
in after the point, but actually triying to access the field fieldname
in data, which doesn't exist.
Instead do:
row=getfield(data, filename);
Upvotes: 5