MATLAB Answers

using a structure as a global variable

106 ビュー (過去 30 日間)
Daniel
Daniel 2017 年 9 月 7 日
編集済み: amin ya 2019 年 9 月 17 日
I want to use a structure as a global variable. This code is an example of the function:
function setGlobalx()
global measBuff
measBuff(1:6) = struct('timeUtc',1,'timePeakOff',2,'peak',3,'mean',4,'eventT',5); %initialize structure
If I call it using:
setGlobalx
global measBuff
display(measBuff)
I get an error on line 3 of the function:
The following error occurred converting from struct to double:
Error using double
Conversion to double from struct is not possible.
Error in setGlobalx (line 3)
measBuff(1:6) = struct('timeUtc',1,'timePeakOff',2,'peak',3,'mean',4,'eventT',5); %initialize structure
Error in Untitled7 (line 3)
setGlobalx
However, if I change the function to:
function setGlobalx2()
measBuff(1:6) = struct('timeUtc',1,'timePeakOff',2,'peak',3,'mean',4,'eventT',5); %initialize structure
global x
x=measBuff
and run
%call function having global variable x
setGlobalx2
global x
display(x);
I get no errors and the structure x is global.
Can anyone tell me why the first method doesn't work? Thanks.

  0 件のコメント

Sign in to comment.

採用された回答

Stephen Cobeldick
Stephen Cobeldick 2017 年 9 月 7 日
編集済み: Stephen Cobeldick 2017 年 9 月 7 日
DO NOT USE GLOBALS.
You could avoid the whole problem by not using globals. Just because some beginners like to use global variables does not make them a good way to code: it makes debugging very difficult, and produces bugs that are quite opaque. Avoid globals, and simply pass your data using any of the preferred and reccomended methods given in the MATLAB documentation: passing arguments, nested functions, etc.:
In any case, your bug is easy to figure out, once you actually read the global documentation, which clearly states that "if the global variable does not exist the first time you issue the global statement, it is initialized to an empty 0x0 matrix."
In your first function the global does not exist at the point where you declare it to be global, then MATLAB creates it as an empty matrix (of the default class double). Clearly an empty matrix does not have elements one to six, and is not a structure, so you attempt to force a structure into it is an error. So, you are basically doing this:
>> A = [];
>> A(1:6) = struct('x',1)
??? The following error occurred converting from struct to double:
Error using ==> double
Conversion to double from struct is not possible.
The solution? Avoid using globals. Pass you data properly.

  0 件のコメント

Sign in to comment.

その他の回答 (1 件)

amin ya
amin ya 2019 年 9 月 17 日
編集済み: amin ya 2019 年 9 月 17 日
Not using globals is not always possible! Such as in App designer when you need to accesss a workspace variable. But you can use
evalin('base','structureName')
to access a structure from workspace, and
assignin('base','structureName',value);
to save to workspace.

  0 件のコメント

Sign in to comment.


Translated by