How to subtract an (n by m) matrix from an (n by m) by k matrix without looping?

10 ビュー (過去 30 日間)
Callum
Callum 2014 年 8 月 5 日
回答済み: Chris Turnes 2014 年 8 月 5 日
Suppose I have the following matrices:
A=[1:4;5:8]
B=randi(10,2,4,3);
I want the same result as the code below gives but without looping, as I intend to use significantly larger sized dimensions which is very slow using looping.
for i=1:3
C(:,:,i)=B(:,:,i)-A;
end
Another method I tried was to concatenate matrix A with itself so that both A and B were the same dimensions before subtraction, but storing A for large dimensions is very memory consuming, not to mention unnecessary.
Cheers.

採用された回答

dpb
dpb 2014 年 8 月 5 日
>> a=eye(2);
>> b=rand(2,2,2)
b(:,:,1) =
0.3500 0.9275
0.2871 0.0513
b(:,:,2) =
0.5927 0.8384
0.1629 0.1676
>> bsxfun(@minus,b,a)
ans(:,:,1) =
-0.6500 0.9275
0.2871 -0.9487
ans(:,:,2) =
-0.4073 0.8384
0.1629 -0.8324
>>

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 5 日
C=bsxfun(@minus,B,A)

Chris Turnes
Chris Turnes 2014 年 8 月 5 日
While bsxfun is the preferred method for doing this, for the sake of completeness in answering the question you can also use indexing:
>> a = eye(2);
>> b = rand(2,2,2);
>> b-a(:, :, ones(2,1))
ans(:,:,1) =
-0.6251 0.8531
0.8449 -0.0829
ans(:,:,2) =
-0.7962 0.6896
0.5438 -0.6952

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by