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

조회 수: 3 (최근 30일)
xd
xd 2024년 12월 4일
댓글: Walter Roberson 2024년 12월 4일
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

채택된 답변

Walter Roberson
Walter Roberson 2024년 12월 4일
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
xd
xd 2024년 12월 4일
but zeros(2*m,2*n); still is double.
Walter Roberson
Walter Roberson 2024년 12월 4일
If necessary you can use something like
zeros(2*m, 2*n, 'like', SOMEVARIABLE)
to make the zeros be the same class as SOMEVARIABLE

댓글을 달려면 로그인하십시오.

추가 답변 (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