필터 지우기
필터 지우기

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 CenterFile Exchange에서 Loops 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