`isscalar`函数适用于用户定义的类

huangapple go评论52阅读模式
英文:

isscalar function for user defined classes

问题

根据文档说明:

isscalar(x)

如果x是一个标量(scalar),则返回true。

标量是一个具有两个维度,其size(x)返回值为[1, 1]的对象。

在Matlab中,这段代码按预期工作。在这里发生了什么?

英文:

I have a class that stores a matrix among other properties.
In the class I overload the size function to return the size of the matrix and that works fine.
The problem is when I use isscalar(a) with a being an instance of the class. This function returns 1 when I was expecting 0.

According to the documentation:
isscalar (x)

Return true if x is a scalar.

A scalar is an object with two dimensions for which size (x) returns [1, 1]

The code works as expected in matlab.
What is going on here?

答案1

得分: 1

你的对象是一个标量:只有一个对象。builtin('size', obj) 会返回 [1,1]。 (请注意,您可以创建对象的数组!)函数 isscalar 实际上并不调用 size,它是一个内置函数,直接访问数组的大小属性,不涉及 M 文件代码执行。 对于诸如 length(返回 max(size()))和 numel(返回 prod(size()))之类的函数也是如此。

但是,您可以像重载 size 一样重载 isscalar,以便它在您的对象内部的矩阵上起作用:

function res = isscalar(obj)
   res = isscalar(obj.matrix);
end

如果您想重载 size 函数,您需要重载一堆其他函数,以保持一致性。

英文:

Your object is a scalar: there is a single object. builtin('size', obj) would return [1,1]. (Note that you can create arrays of objects!) The function isscalar doesn't actually call size, it is a builtin function that has direct access to the size property of the array, no M-file code execution is involved. The same is true for functions such as length (which returns max(size())) and numel (which returns prod(size())).

But you can overload isscalar just like you overloaded size to work on the matrix inside your object instead:

function res = isscalar(obj)
   res = isscalar(obj.matrix);
end

If you want to overload the size function, you need to overload a bunch of other functions too, in order for things to remain consistent.

huangapple
  • 本文由 发表于 2023年3月9日 18:30:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定