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));

 Accepted Answer

tmp = bsxfun(@times, norm_mode, reshape(fields(:,3),1,1,[]))

3 Comments

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

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2023a

Community Treasure Hunt

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

Start Hunting!