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!