关于 ndgrid 如何用正整数参数 生成 浮点数网格坐标数组, 然后用 hypot 计算矢量长度度, 出错 ?

3 views (last 30 days)
xd
xd on 4 Dec 2024
Commented: Walter Roberson on 4 Dec 2024
ndgrid 生成网格坐标数组, 然后用 hypot 计算矢量尺度, 出错 !
在函数内部,指定了参数类型(因为要用于被C++调用),此时ndgrid生成的是坐标数组X Y竟然也是uint16数组(为什么与索引m n类型相关??),但hypot要求输入是浮点数数组,于是出错 !
intdou(3,3)
function intdou(m,n)
arguments
m uint16
n uint16
end
[Y,X] = ndgrid(1:m,1:n); % 若m nu时uint,X Y也是 uint!???
rad = hypot(X-n,Y-m); % hypot 要求参数必须时double ,出错 !
whos m n X Y rad
end
下面代码是正确可执行的,但此函数是为被C++调用设计必须指明参数类型uint。
function intdou(m,n)
arguments
m double %uint16
n double %uint16
end
[Y,X] = ndgrid(1:m,1:n);
rad = hypot(X-n,Y-m);
whos m n X Y rad
end
好奇葩! 似乎是 ndgrid设计为 输入和输出是同类型。
似乎我必须得这样设计一次转换, 才能保证 X Y是double矩阵:
function intdou(m,n)
arguments
m uint16
n uint16
end
[Y,X] = ndgrid(1:0.5:double(m),1:0.5:double(n)); % ndgrid 不能用dpuble做参数, 出错 !
rad = hypot(X-double(n),Y-double(m)); % % hypot 要求参数必须时double
whos m n X Y rad
end

Accepted Answer

Walter Roberson
Walter Roberson on 4 Dec 2024
Yes, ndgrid with two outputs is designed to have the same output type as input type. Well, except that sparse matrices are promoted to full matrices.
However, you could do
function intdou(m,n)
arguments
m uint16
n uint16
end
[Y,X] = ndgrid(1:mm,1:nn); %
rad = hypot(double(X)-double(n),double(Y)-double(m)); %
end
  3 Comments
xd
xd on 4 Dec 2024
but zeros(2*m,2*n); still is double.
Walter Roberson
Walter Roberson on 4 Dec 2024
If necessary you can use something like
zeros(2*m, 2*n, 'like', SOMEVARIABLE)
to make the zeros be the same class as SOMEVARIABLE

Sign in to comment.

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!