Search code examples
matlabtext-filesworkspace

how to compare string from .txt file with workspace in Matlab


I'm having a .txt file like this:

structure
a = title
c1 = A.B.C
endstructure

I want to read this to matlab and then check if in my workspace already exists a structure named A.B.C. if so, then I want to save data from this structure to variable c1. I have problem with proper parsing the line c1 = A.B.C and then comparing it with workspace. any help appreciated.

              • explanation - - - - - - in my workspace there is a structure A.B.C. = [0 1 2 3 5 8] in my txt file I write c1 = A.B.C, and that is the name. I want in my program to check if this name matches some already existing data with this name in the workspace. if so, assign this data to a variable c1 and leave c1 in the workspace.


Solution

  • To determine if your variable already exists in the Matlab workspace, you can use matlab exist function. It would be a little awkward in your situation though as you can only check to see if variable 'A' exists. You could then nest it further and see if the variable has the specified field. It could look like this:

    if( exist('A','var') && isfield(A,'B') && isfield(A.B,'C') )
         %do something
    end