How to write a line of statement with two vector of different size using no loops

1 回表示 (過去 30 日間)
Istiaq Ansari
Istiaq Ansari 2017 年 10 月 22 日
コメント済み: Cedric 2017 年 10 月 24 日
I am not sure if the title us correct. But here's what i want to do.
n = -10:10;
p = [-0.6 0.2];
r = [ -1.7500 2.7500];
H = zeros(size(n));
for i=1:length(p)
H = H + r(i)*(p(i).^n).*(n>=0);
end
I want to write this for loop in one line of statement. Is there a way?

採用された回答

Cedric
Cedric 2017 年 10 月 22 日
編集済み: Cedric 2017 年 10 月 22 日
>> H2 = (n >= 0) .* sum(r.' .* p.'.^n) ;
>> isequal( H2, H )
ans =
logical
1
if it doesn't work, you may have a MATLAB version < 2016b. In such case:
>> H3 = (n >= 0) .* sum(bsxfun(@times, r.', bsxfun(@power, p.', n))) ;
>> isequal( H3, H )
ans =
logical
1
  2 件のコメント
Istiaq Ansari
Istiaq Ansari 2017 年 10 月 24 日
Thanks a lot. I currently have matlab 2016a. Now i guess i am going to switch to newer version.
Cedric
Cedric 2017 年 10 月 24 日
My pleasure! It's worth getting the latest version if it is distributed at your institution, because a lot of new features appeared between 2016b and 2017b. Here in my first solution we use an implicit automatic expansion for example, using a very simple syntax.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by