Why This Vectorization of my Code Does Not Work?

1 回表示 (過去 30 日間)
Kareem Elgindy
Kareem Elgindy 2020 年 7 月 14 日
編集済み: Kareem Elgindy 2020 年 7 月 14 日
Consider the following two codes:
n = 4;
% Code 1:
c1 = zeros(floor(n/2)+1,n+1); c1(1,1) = 1; c1(1,2:n+1) = 2.^(0:n-1);
for k = 2:n
for l = 1:floor(k/2), c1(l+1,k+1) = -((k - 2*l + 2)/(4*l*(k - l)))*(k - 2*l + 1)*c1(l,k+1); end
end
c1
% Code 2:
c2 = zeros(floor(n/2)+1,n+1); c2(1,1) = 1; c2(1,2:n+1) = 2.^(0:n-1);
for k = 2:n
lend = floor(k/2); c2(2:lend+1,k+1) = -((k-2*(1:lend)+2)./(4*(1:lend).*(k-(1:lend)))).*(k-2*(1:lend)+ 1).*c2(1:lend,k+1)';
end
c2
The first code gives
while the second gives

回答 (1 件)

KSSV
KSSV 2020 年 7 月 14 日
Might be some problem with indexing. Try this:
clc; clear all ;
n = 4;
% Code 1:
c1 = zeros(floor(n/2)+1,n+1);
c1(1,1) = 1;
c1(1,2:n+1) = 2.^(0:n-1);
for k = 2:n
for l = 1:floor(k/2)
c1(l+1,k+1) = -((k - 2*l + 2)/(4*l*(k - l)))*(k - 2*l + 1)*c1(l,k+1);
end
end
c1
% Code 2:
c2 = zeros(floor(n/2)+1,n+1);
c2(1,1) = 1;
c2(1,2:n+1) = 2.^(0:n-1);
for k = 2:n
lend = floor(k/2);
% c2(2:lend+1,k+1) = -((k-2*(1:lend)+2)./(4*(1:lend).*(k-(1:lend)))).*(k-2*(1:lend)+ 1).*c2(1:lend,k+1)';
l = 1:lend ;
c2(2:lend+1,k+1) = -((k - 2*l + 2)./(4*l.*(k - l))).*(k - 2*l + 1).*c1(l,k+1)';
end
c2
  1 件のコメント
Kareem Elgindy
Kareem Elgindy 2020 年 7 月 14 日
編集済み: Kareem Elgindy 2020 年 7 月 14 日
Works like a charm :-). But what is wrong in indexing in the previous code?... I still don't get it!! One more thing. In your 2nd code you used c1. In fact, c2 is calculated using previous values of c2 only not c1.

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

カテゴリ

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

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by