2

I want to compare two strings from two structs. My Code is like below:

%matlab model scan

[variables] = Simulink.findVars('myModell');
variablesNames =[];

%save the names of all the variables in variablesNames
for t= 1:length(variables)
     variablesNames(t).Name = variables(t).Name;   
end

%scan workspace
for f = fieldnames(my_workspace)
    found = false;
    for c = 1:length(variablesNames)
        if strcmp(f{c}, variablesNames(c))        
            found = true;
            result = 'Found in Workspace: ';
        end    
        if ~found
            result = 'Not found inside Workspace';
        end
    end
    disp(['Workspace Variable: ', sprintf('%-*s',40,f{c}), result]);
end

variablesNames is a struct 1x15 with 1 field

my_workspace is 1x1 struct with 20 fields

I got only one variable as return. What is wrong in this code?

4
  • f = fieldnames(my_workspace) ? do you mean f = 1:numel(fieldnames(my_workspace))? Commented Jul 1, 2016 at 11:48
  • You mean only one value in result? That's pretty normal as you override it everytime you loop. Try changing result to result{c} Commented Jul 1, 2016 at 11:54
  • @Ander Biguri : I tried your suggestion, but please consider that f is a 20x1 cell . Here is the failure:Cell contents reference from a non-cell array object. Error in stackoverflow (line 13) if strcmp(f{c}, variablesNames(c)) Commented Jul 1, 2016 at 12:02
  • @BillBokeey: I also tried. But result contains only one variable (number 5) from variablesNames Commented Jul 1, 2016 at 12:05

1 Answer 1

2

I don't really understand why are you creating a new struct here: variablesNames(t).Name, therefore I just removed that part.

The modified code just iterates through the variables struct-array and checks whether variable my_workspace has a field with the name of the value stored in the Name field of the currently processed element, using isfield.

[variables] = Simulink.findVars('myModell');

for i = 1:length(variables)
   if isfield(my_workspace, variables(t).Name)
      result = 'Found in Workspace: ';
   else
       result = 'Not found inside Workspace';
   end

   disp(['Workspace Variable: ', sprintf('%-*s', 40, variables(t).Name), result]);
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.