How to solve type mismatch error when assigning variable to class in conditional?
7 次查看(过去 30 天)
显示 更早的评论
Example Code:
1 flag = true;
2 if flag
3 this.prop = TFlag();
4 else
5 this.prop = FFlag();
6 end
Error Code:
Type name mismatch: TFlag ~= FFlag.
In the diagnostic report, the error is shown in line 5, where this.prop cannot be assigned FFlag() because it is understood as a varible of class type TFlag().
Question:
It appears that this.prop is being intialized as a variable of class type TFlag regardless of the condition, and I am unable to run this conditional. It should also be noted that the constructor method of each of these classes returns a struct(), but they are different sizes. TFlag returns a struct of size 30, and FFlag returns a struct of size 10.
0 个评论
采纳的回答
David Fink
2024-7-9
In code generation, since the generated code is statically typed, the type of this.prop must be determined at code generation time.
When processing the first assignment to this.prop, it assigns its type as TFlag. Then when processing the second assignment, it produces the type mismatch error you observed, as FFlag is a different class type than TFlag.
It is possible to assign two distinct values with the same type, but different sizes. For example:
if runtimeCond
s = struct('f', 0); % 1x1 struct, field f = 1x1 double
this.prop = s;
else
s2 = struct('f', {1, 2}); % 1x2 struct array, field f = 1x1 double
this.prop = s2;
end
See also:
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!