How can I assign zeros to a particular value in an expression

1 回表示 (過去 30 日間)
University Glasgow
University Glasgow 2022 年 8 月 10 日
編集済み: Matt J 2022 年 8 月 10 日
Is it possible to assign zeros to following entries: u(N-N), u(N) i.e u(0) and u(4) in the loop below?
N =4;
u = (1:N);
v = (N:2*N-2);
for i=2:N
rhsode(i,1)=(u(i)-2*u(i-1)+u(i-2))+(v(i)-v(i-2))
end
  1 件のコメント
dpb
dpb 2022 年 8 月 10 日
No. MATLAB arrays are 1-based indexing (1:N) and that is inviolate (unlike C which is 0-based (0:N-1) and also inviolate). Fortran has the facility to define arrays with arbitrary indexing (although the default is also 1-based); unfortunately, The MathWorks chose to not bring that faciility over.
You can only address elements u(1) through u(4) and v(1) through v(3) based on N=4 above.

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

採用された回答

Bruno Luong
Bruno Luong 2022 年 8 月 10 日
test
rhsode = 2×1
0 5
rhsode = 3×1
0 5 2
rhsode = 4×1
0 5 2 -9
function test
N =4;
u = (1:N);
v = (N:2*N-2);
function ui = getu(i)
if i <= 0 | i >= 4
ui = 0;
else
ui = u(i);
end
end
function vi = getv(i)
if i <= 0 | i >= 4
vi = 0;
else
vi = v(i);
end
end
for i=2:N
rhsode(i,1)=(getu(i)-2*getu(i-1)+getu(i-2))+(getv(i)-getv(i-2))
end
end

その他の回答 (1 件)

Matt J
Matt J 2022 年 8 月 10 日
編集済み: Matt J 2022 年 8 月 10 日
N =8;
u = [0,(1:N-1),0];
v=N:N-1+numel(u);
rhsode=diff(u,2)+v(3:end)-v(1:end-2)
rhsode = 1×7
2 2 2 2 2 2 -6
  4 件のコメント
dpb
dpb 2022 年 8 月 10 日
What do you expect the the results to be?
Internally with the various builtin functions like <polyval> and friends, MATLAB represents a polynomial as a row vector with coefficients in descending powers with missing terms explicitly represented by 0 in the appropriate position. But, vectors in MATLAB are still 1-based addressing so
p=[1 -4 4];
would be the representation of quadratic x.^2 - 4*x + 4
But, it's totally unclear what your code is intended to produce...
Matt J
Matt J 2022 年 8 月 10 日
編集済み: Matt J 2022 年 8 月 10 日
Sorry, I still didn't understand this. How can I relate this to my for loop to give me 3 polynomials since I want u_1, u_2 and u_3?
The code you've posted aims to generate an output rhsode of length N-1. That is what my code does.
It is not clear however what boundary conditions you intended on v, so I just assumed in my examples that it was to be extrapolated linearly.

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

カテゴリ

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

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by