Elegant way to create dynamically an array inside a for loop ?

Check the following piece of code.
r = magic(5);
w = bartlett(5);
for j=1:10
b1(j)=sum(r(1,:).*w'*j);
b2(j)=sum(r(2,:).*w'*j);
b3(j)=sum(r(3,:).*w'*j);
b4(j)=sum(r(4,:).*w'*j);
b5(j)=sum(r(5,:).*w'*j);
end
b = [b1;b2;b3;b4;b5];
each b1,b2,b3,b4,b5 is a vector of size 1x10 and the final result I am looking for is a vector b of size 5x10 .
I was wondering if there is a more robust way to create b rather than the paradigm above.

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 14 日
編集済み: Azzi Abdelmalek 2014 年 12 月 14 日

0 投票

d=sum(bsxfun(@times,repmat(bsxfun(@times,r',w)',1,1,10),reshape(1:10,1,1,[])),2)
b=d(:,:);

6 件のコメント

Stamatis Samaras
Stamatis Samaras 2014 年 12 月 14 日
Error using ==> repmat
Too many input arguments.
Stamatis Samaras
Stamatis Samaras 2014 年 12 月 14 日
編集済み: Stamatis Samaras 2014 年 12 月 14 日
repmat(bsxfun(@times,r',w)',1,10) is this correct?
Stamatis Samaras
Stamatis Samaras 2014 年 12 月 14 日
by changing repmat as shown above d is 5x1x10 which is ok. I can make it 5x10 but all values are multiplied by 10 on the final result.
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 14 日
There is no error in my code
r = magic(5);
w = bartlett(5);
d=sum(bsxfun(@times,repmat(bsxfun(@times,r',w)',1,1,10),reshape(1:10,1,1,[])),2)
b=d(:,:)
Stamatis Samaras
Stamatis Samaras 2014 年 12 月 14 日
This is really strange but I keep on getting the same error,
Error using ==> repmat
Too many input arguments.
Stamatis Samaras
Stamatis Samaras 2014 年 12 月 14 日
By splitting each function in different parts and then combining them the final result is the one I am looking for! I still dont get why my MATLAB version dont want to compile the whole thing but its ok! Anyway thanks a lot for you time and effort !

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by