help using bsxfun to multiplay different size matrixes

I want to make the following:
create a matrix that has one more diamention the the matrix norm_mode (actuatty is to make a norm_mode a time function)
to accelrate it on matlab I tryied the use of bsxfun, but I get the error : "Non-singleton dimensions of the two input arrays must match each other."
Please help me fix it, I cant tell where the problem is.
tmp = zeros(newSize, newSize, length(others.t));
for idx_t = 1:length(t)
tmp(:,:,idx_t) = norm_mode(:,:) .* fields(idx_t,3) ;
end
tmp = bsxfun(@times, norm_mode, fields(:, ii));

 Respuesta aceptada

Stephen23
Stephen23 el 20 de Mayo de 2024
Editada: Stephen23 el 20 de Mayo de 2024
tmp = bsxfun(@times, norm_mode, reshape(fields(:,3),1,1,[]))

3 comentarios

Thanks for the help
when I'm trying to apply it, I get the error "Size can only have one unknown dimension" for the reshape function.
I will add the all function mybe it will be clearer
function total_field = BuildSpatialField(fields,fiber, sim, others)
t = others.t;
lambda = sim.lambda0;
% downsample the spatial picture by a factor of n^2
n = 4;
if mod(others.Nx, n) ~= 0
error('Matrix size must be divisible by n');
end
newSize = others.Nx / n;
% TODO: add all z
total_field = zeros( newSize, newSize, length(others.t) ); % total_field(X,Y,t)
h = waitbar(0, 'calculate field...');
% TODO: try using parfor loop
for ii=1:others.modes
% load mode spashial profile
fname=[fiber.MM_folder 'radius' strrep(num2str(fiber.radius), '.', '_') 'boundary0000fieldscalar'...
'mode' num2str(ii,'%03.f') 'wavelength' strrep(num2str(lambda*1e9), '.', '_')];
phi = load([ fname '.mat'], 'phi');
phi = phi.phi;
phi_downsampled = downsample_matrix(phi, n);
% normalize the field norm
norm_mode = (phi_downsampled) ./ sqrt((sum(sum(abs(phi_downsampled).^2))));
% tmp = zeros(newSize, newSize, length(others.t));
% for idx_t = 1:length(t)
% tmp(:,:,idx_t) = norm_mode(:,:) .* fields(idx_t,ii) ;
% end
tmp = bsxfun(@times, norm_mode, reshape(fields(:,ii),[],[],1));
total_field = total_field + tmp;
waitbar(ii/others.modes, h, ['mode ' num2str(ii) ' from ' num2str(others.modes)]);
end
close(h);
end
@barak messica: I edited my answer.
Works
Thanks :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Productos

Versión

R2023a

Etiquetas

Preguntada:

el 20 de Mayo de 2024

Comentada:

el 20 de Mayo de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by