avoding loops by vectorization

5 ビュー (過去 30 日間)
Lee
Lee 2011 年 6 月 29 日
Hello,
I am trying to rewrite a for loop by using vectors. The loop is:
for i=1:8 outer_x(i,:)=x_i(i)+d_del(1,i)*cos(t); end
where d_del is 2x8, x_i is 1x8, and cos(t) is 1x6284
The loop does the following: outer_x(1,:)=x_i(1)+d_del(1,1)*cos(t); outer_x(2,:)=x_i(2)+d_del(1,2)*cos(t); outer_x(3,:)=x_i(3)+d_del(1,3)*cos(t); etc
I tried the following: x_i(1:end)+d_del(1,(1:end))*cos(t);
I was hoping to take each entry of d_del and multiply with every entry of cos(t), but it does not work. Any help will be greatly appreciated!
  1 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 6 月 29 日
You say d_del = 2x8; do you use only the first row? You never access d_del(2,anything)

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

回答 (4 件)

Oleg Komarov
Oleg Komarov 2011 年 6 月 29 日
outer_x = bsxfun(@plus, x_i, d_del(1,:)*cost.');
Don't use cos (i renamed it in cost) as a variable since it's already a builtin matlab function. If t is the 1 by 6284 variable then ignore my previous comment.
  1 件のコメント
Matt Fig
Matt Fig 2011 年 6 月 29 日
I believe that lee meant to take the cosine of a vector t...

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


Andrei Bobrov
Andrei Bobrov 2011 年 6 月 29 日
outer_x = bsxfun(@plus,d_del(1,:)'*cos(t),x_i');
  2 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 6 月 29 日
Nice Answer! :)
Andrei Bobrov
Andrei Bobrov 2011 年 6 月 29 日
all +1

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


Sean de Wolski
Sean de Wolski 2011 年 6 月 29 日
outer2 = bsxfun(@plus,(d_del(1,:).')*cos(t),x_i.');
produces the same result as your loop.
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 6 月 29 日
O! Strong volley!

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


Laura Proctor
Laura Proctor 2011 年 6 月 29 日
This should do it:
outer_x_new = x_i'*ones(size(t))+d_del(1,:)'*cos(t);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by