Hi All I have two large matrix and I want to calculate an expression without for loop. this expression is something like matrix d as below
f=[f1 f2 f3]
r=[r1 r2 r3]
d=[f1-r1 f2-r1 f3-r1
f1-r2 f2-r2 f3-r2
f1-r3 f2-r2 f3-r3]
can any one help me?! consider that size(f)=1*1*400 and size(r)=50*50*900 and fii=f(1,1,ii) and rjj=r(:,:,jj)

 採用された回答

Stephen23
Stephen23 2015 年 1 月 20 日
編集済み: Stephen23 2015 年 1 月 21 日

2 投票

You gave this code in a comment to my other answer:
size(f)==[1,350]
size(r)==[50,50,900]
for ii=1:350
for jj=1:900
s(ii,jj) = sum(sum(sum( repmat(f(ii),[50,50,1]) - r(:,:,jj) ))) ;
end
end
You can try this instead:
A = 50*50*reshape(f,1,[]);
B = reshape(sum(sum(r,1),2),[],1);
C = bsxfun(@minus,A,B);
It produces the same result as your nested loops.

1 件のコメント

rahman
rahman 2015 年 1 月 25 日
tnx Stephen Cobeldick. your code was completely helpfull ;)

サインインしてコメントする。

その他の回答 (2 件)

Stephen23
Stephen23 2015 年 1 月 20 日
編集済み: Stephen23 2015 年 1 月 20 日

1 投票

This is exactly what bsxfun is for:
f = [f1,f2,f3];
r = [r1,r2,r3];
d = bsxfun(@minus,f,r.');
bsxfun calculates the output without requiring large intermediate arrays (eg using repmat). Although, depending on the size of d, you might still run out of memory...

3 件のコメント

rahman
rahman 2015 年 1 月 20 日
編集済み: rahman 2015 年 1 月 20 日
Dear friends let me say exactly what I need ! suppose that size(f) = 1*350 ; size(r)=50*50*900; I want to calculate the S matrix as below
for ii=1:350
for jj=1:900
s(ii,jj) = sum(sum(sum( repmat(f(ii),[50,50,1]) - r(:,:,jj) ))) ;
end
end
Now, I want to calculate this matrix without for loops and by faster matrix calculation method !
Stephen23
Stephen23 2015 年 1 月 20 日
編集済み: Stephen23 2015 年 1 月 20 日
What you have now described is a different problem to the one that you posed in your original question. My code exactly solves your original question.
John D'Errico
John D'Errico 2015 年 1 月 20 日
The heartache of those who write code - shifting specs. The correct answer to the question asked but not the question intended. :)

サインインしてコメントする。

dpb
dpb 2015 年 1 月 20 日

0 投票

d=repmat(f,size(r,2),1).-repmat(r.',1,size(f,2));

1 件のコメント

rahman
rahman 2015 年 1 月 20 日
tnx dpb but this operation needs much RAMs according to what I said ( consider that size(f)=1*1*400 and size(r)=50*50*900 and fii=f(1,1,ii) and rjj=r(:,:,jj) )

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 1 月 20 日

コメント済み:

2015 年 1 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by