Can we use implicit array expansion across = sign?

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

Prodotti


Release

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by