Prateek Verma
Prateek Verma

Reputation: 115

Matlab: How to remove the error of non-existent field

I am getting an error when running matlab code. Here I am trying to use one of the outputs of previous code as input to my new code.

??? Reference to non-existent field 'y1'.

Can anyone help me?

Upvotes: 1

Views: 19545

Answers (4)

shawon
shawon

Reputation: 1022

At first load it on command window and observe the workspace window. You can see the structure name. It will work by accessing structure name. Example:

lm=load('data.mat');
disp(lm.SAMPLE.X);

Here SAMPLE is the structure name and X is a member of the structure

Upvotes: 0

Moon Zoe
Moon Zoe

Reputation: 53

I would first explain my situation and then give the solution.

  • I first save a variable op, it is a struct , its name is coef.mat;
  • I load this variable using coef = load( file_path, '-mat');
  • In a new function, I pass variable coef to it as a parameter, at here, the error Reference to non-existent field pops out.

My solution:

  • Just replace coef with coef.op, then pass it to the function, it will work.

So, I think the reason behind is that: the struct was saved as a variable, when you use load and want to acess the origin variable, you need point it out directly using dot(.) operation, you can directly open the variable in Matlab workspace and find out what it wraps inside the variable.

In your case, if your the outputs of previous code is a struct(It's my guess, but you haven't pointed out) and you saved it as MyStruct, you load it as MyInput = load(MyStruct), then when use it as function's parameter, it should be MyInput.y1.

Hops it would work!

Upvotes: 0

Ahmad Hassanat
Ahmad Hassanat

Reputation: 425

Have you used the command load to load data from file(s)? if yes, this function overwrite your current variables, therefore, they become non-existent, so when you call, it instead of using:

load ('filename');

use:

f=load ('filename');

now, to refer to any variable inside the loaded file use f.varname, for example if there is a network called net saved within the loaded data you may use it like:

a = f.net(fv);

Upvotes: 1

Shai
Shai

Reputation: 114866

A good practice might be to check if the field exists before accessing it:

if isfield( s, 'y1' )
    % s.y1 exists - you may access it
    s.y1
else
    % s.y1 does not exist - what are you going to do about it?
end

To take Edric's comment into account, another possible way is

try 
    % access y1
    s.y1
catch em
    % verify that the error indeed stems from non-existant field
    if strcmp(em.identifier, 'MATLAB:nonExistentField')
         fprintf(1, 'field y1 does not exist...\n');
    else
         throw( em ); % different error - handle by caller?
    end
end

Upvotes: 3

Related Questions