正如在另一个答案中所说,有时您可以简单地在函数中输入一个数组。但是根据您的函数执行的操作,您可能会得到错误的结果。如果您想避免这种情况,您可以简单地定义自己的arrayfun,如下所示:
function B = matrixfun(func,A)
for i = 1 : size(A,'r')
for j = 1 : size(A,'c')
B(i,j) = func(A(i,j))
end
end
endfunction
我称它为matrixfun,因为它更通用。例如,考虑一个 toHex 函数,它将实数 x 转换为将其表示为十六进制的字符串。
function s = toHex(n)
s = "";
n = round(n)
if n == 0 then
s = "0";
else
while n >= 1
select modulo(n,16)
case 15 then s = "F" + s
case 14 then s = "E" + s
case 13 then s = "D" + s
case 12 then s = "C" + s
case 11 then s = "B" + s
case 10 then s = "A" + s
else s = string(modulo(n,16)) + s;
end
n = floor(n / 16)
end
end
endfunction
A = grand(4,4,"uin",0,50); //random matrix
B = toHex(A);
C = matrixfun(toHex,A);
您可以在控制台中查看结果:
--> disp(A) //原始随机矩阵
37. 14. 4. 42.
17. 2. 18. 48.
23. 37. 31. 21.
16. 39. 43. 17.
--> disp(B) //错误的结果
!5 14 4 10 !
! !
!1 2 2 0 !
! !
!7 5 15 5 !
! !
!0 7 11 1 !
--> disp(C) //正确的结果
!25 E 4 2A !
! !
!11 2 12 30 !
! !
!17 25 1F 15 !
! !
!10 27 2B 11 !