subtracting matrices with different dimensions
显示 更早的评论
Hello im just practicing some stuff on Matlab and I have a stupid question.
So i have two matrices Xtest and Xmean.
Xtest is 45 x 4
Xmean is 1x4 which is lets say [1,2,3,4]
I want to subtract 1 from each row of column 1 of Xtest and 2 from each row of column 2 and so on.
What would be the simplest way to go about this. i cant just do Xtest - Xmean because the dimensions are wrong.
回答(1 个)
Star Strider
2016-4-26
Use the bsxfun function. It does exactly what you want:
Xtest = randi(9, 45, 4);
Xmean = [1,2,3,4];
Result = bsxfun(@minus, Xtest, Xmean);
The bsxfun function expands the singleton dimension of ‘Xmean’ to the dimensions of ‘Xtest’ and then does the subtraction.
You could do the same thing by using repmat on ‘Xmean’ and then doing the subtraction, but bsxfun is much more efficient and much faster.
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!