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

조회 수: 1(최근 30일)
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);
I want to write this for loop in one line of statement. Is there a way?

채택된 답변

Cedric Wannaz
Cedric Wannaz 2017년 10월 22일
편집: Cedric Wannaz 2017년 10월 22일
>> H2 = (n >= 0) .* sum(r.' .* p.'.^n) ;
>> isequal( H2, H )
ans =
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 =
  댓글 수: 2
Cedric Wannaz
Cedric Wannaz 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개)

Community Treasure Hunt

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

Start Hunting!

Translated by