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

采纳的回答

Matt J
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 个评论
Mike
Mike 2023-12-27
Now that’s interesting (= unexpected). Thanks for the advice and quick assistance!
Matt J
Matt J 2023-12-27
You're quite welcome, but if this resolves your question, please Accept-click the answer.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by