Can we use implicit array expansion across = sign?
2 次查看(过去 30 天)
显示 更早的评论
I recently started to port some of my MATLAB scripts to numpy/python and found a difference between MATLAB implicit array expansion and numpy/python broadcasting.
Here's my working python code:
# >>>>> calculate COORD (use broadcast)
coord = np.zeros((ny+1, nx+1, 6))
coord[:, :, [0, 3]] = x0 - dx/2 + dx*np.arange(nx+1).reshape([1, -1, 1])
coord[:, :, [1, 4]] = y0 - dy/2 + dy*np.arange(ny+1).reshape([-1, 1, 1])
coord[:, :, [2, 5]] = z0 - dz/2 + dz*np.array([0, nz+1]).reshape([1, 1, 2])
Here's my equivalent MATLAB code:
coord=zeros(6,nx+1,ny+1);
coord([1 4],:,:)=x0-dx/2+dx*repmat(reshape((0:nx),1,[],1),[2 1 ny+1]);
coord([2 5],:,:)=y0-dy/2+dy*repmat(reshape((0:ny),1,1,[]),[2 nx+1 1]);
coord([3 6],:,:)=z0-dz/2+dz*repmat(reshape([0,nz],[],1,1),[1 nx+1 ny+1]);
So, in the spirit of increasing my MATLAB skills, two questions:
1/ Is there a way to coax MATLAB to perform implicit array expansion across the "=" sign, to match the simplicity of the numpy/python broadcast calculation?
2/ Does it matter? Is the memory overhead in using repmat irrelevant?
My thanks in advance, for advice!
Mike
0 个评论
采纳的回答
Matt J
2023-12-26
编辑:Matt J
2023-12-27
2/ Does it matter? Is the memory overhead in using repmat irrelevant?
It could matter. Most people would probably not bother to optimize it, but you could use a for-loop instead of repmat, e.g.,
tmp=x0-dx/2+dx*(0:nx);
for i=[1,4], coord(i,:)=tmp; end
This should have no memory allocation overhead.
1/ Is there a way to coax MATLAB to perform implicit array expansion across the "=" sign, to match the simplicity of the numpy/python broadcast calculation?
No, unfortunately. But as shown above, you can avoid reshape() in this case.
6 个评论
Matt J
2023-12-27
You're quite welcome, but if this resolves your question, please Accept-click the answer.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!