Why do variables that are declared as globals get set to doubles?

3 次查看(过去 30 天)
The variables that are declared as globals get set to doubles. This makes a consistent programming style difficult.
a.b = 3;
c(1) = a;
% Here c is a structure, however, if you do
global d
d(1) = a;
% You get an error stating ??? Conversion to double from struct is not possible.

采纳的回答

MathWorks Support Team
The reason you get this error with global (or persistent) variables is that all global/persistent variables are implicitly initialized to []. Since the types need to match during subscripted assignment you get the error. In order to eliminate this error you can:
1. Avoid using the subscript (since the subscripted assignment preserves the original type)
2. Initialize d to be a struct. In this case you could use:
global d;
if isempty(d)
d = struct([]);
end
The basic idea behind suggestion 2 is that you need to create the variable to be a data type in the class of your choice. Then subscripted assignments into it will produce the results you'd like.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by