Can we use implicit array expansion across = sign?
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt J
on 26 Dec 2023
Edited: Matt J
on 27 Dec 2023
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 Comments
Matt J
on 27 Dec 2023
You're quite welcome, but if this resolves your question, please Accept-click the answer.
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!