How can I assign zeros to a particular value in an expression
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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
2022년 8월 10일
test
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
댓글 수: 0
추가 답변 (1개)
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)
댓글 수: 4
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
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 Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!