如何在Matlab中沿着带有矢量的轴划分矩阵 - 或进行其他算术运算?
示例:
M = [2 4 6 ; ...
8 4 2 ];
v = [2 4 2];
d = M/v; % divide along first axis
d =
1 1 3
4 1 1
答案 0 :(得分:5)
使用@rdivide
选项完美设置 bsxfun
,让v
内部扩展为M
,然后执行元素划分 - < / p>
d = bsxfun(@rdivide,M,v)
基准代码
N_arr = [100 200 500 1000 2000 4000];
timeall = zeros(4,numel(N_arr));
for k1 = 1:numel(N_arr)
N = N_arr(k1);
M = rand(N,N);
v = rand(1,N);
f = @() bsxfun(@rdivide,M,v);
timeall(1,k1) = timeit(f);
clear f
f = @() M ./ repmat(v, size(M, 1), 1);
timeall(2,k1) = timeit(f);
clear f
f = @() M ./ ( ones(size(M,1),1)*v );
timeall(3,k1) = timeit(f);
clear f
f = @() ele_div(M,v);
timeall(4,k1) = timeit(f);
clear f
end
figure,hold on,grid on
plot(N_arr,timeall(1,:),'-ro'),plot(N_arr,timeall(2,:),'-kx')
plot(N_arr,timeall(3,:),'-g+'),plot(N_arr,timeall(4,:),'-b.')
legend('BSXFUN','REPMAT','ONES','FOR-LOOP'),
xlabel('Datasize ->'),ylabel('Time(sec) ->')
相关功能
function MM = ele_div(M,v)
MM = zeros(size(M));
for i=1:size(M,1)
MM(i,:) = M(i,:) ./ v;
end
return;
基准测试结果
答案 1 :(得分:2)
几种方式:
%# FOR-loop
MM = zeros(size(M));
for i=1:size(M,1)
MM(i,:) = M(i,:) ./ v;
end
%# BSXFUN
MM = bsxfun(@rdivide, M, v);
%# REPMAT
MM = M ./ repmat(v,size(M,1),1);
%# repetition by multiplication
MM = M ./ ( ones(size(M,1),1)*v );
答案 2 :(得分:0)
您可以使用repmat
使v
与M
具有相同的维度:
d = M ./ repmat(v, size(M, 1), 1)