Global structs possible?

Dear Ladies, dear Gentlemen,

I write a program for Octave and would like to store the relevant data in on struct variable. As I need to handle this struct variable also by callbacks I tried to declare it as global. But I got error messages like:

error: operator =: no conversion for assignment of ‘scalar struct’ to indexed ‘matrix’

Is it possible to use a global struct and how can I declare this correctly?

Regards,

Paul Pixner

Works for me:

>> global my_settings
>> my_settings = struct();
>> my_settings.prop1 = 1;
>> clear my_settings
>> global my_settings
>> my_settings.prop1
ans = 1

Thanks for your example. In meantime I could define my issue better: it seems that global struct arrays either not work or need special assignment. My example:

function rv = mytst(n)
%% Just to create some numbers
x.a = n;
x.b = n+1;
rv = x;
endfunction

global test;
for(i=1:5)
  test(i)=mytst(i);
endfor

This will create the error msg:
error: operator =: no conversion for assignment of 'scalar struct' to indexed 'matrix'

Regards,

Paul

“test” is an internal octave function (see “help test”) ; “i” is a built-in function (see “help i”) .
Shadowing those is a bad style though not a critical mistake.

Replacing “test(i) = mytst(i)” with “test{i} = mytst(i)” seems to fix the problem with your code.

octave:3> function rv = mytst(n)
%% Just to create some numbers
x.a = n;
x.b = n+1;
rv = x;
endfunction
octave:4> global test;
for(i=1:5)
test(i)=mytst(i);
endfor

error: operator =: no conversion for assignment of 'scalar struct' to indexed 'matrix'
octave:6> global test;
for(i=1:5)
test{i}=mytst(i);
endfor
octave:8> test
test =
{
  [1,1] =

    scalar structure containing the fields:

      a = 1
      b = 2

  [1,2] =

    scalar structure containing the fields:

      a = 2
      b = 3

  [1,3] =

    scalar structure containing the fields:

      a = 3
      b = 4

  [1,4] =

    scalar structure containing the fields:

      a = 4
      b = 5

  [1,5] =

    scalar structure containing the fields:

      a = 5
      b = 6

}

Thank you very much. I think this will solve my issue. And I will rename the “test” variable :slight_smile:

Regards,

Paul

A global variable is initialized as an empty matrix. You cannot assign a struct to a matrix with an index expression.
Alternatively to what @dasergatskov wrote, you could change the type to a struct first before indexing into it. E.g., in your example, you could change the lower part to:

global test;
test = mytst(1);
for ii = 2:5
  test(ii) = mytst(i);
endfor

Thanks, that helps also. Now I have two alternatives.

Regards,

Paul