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

1 visualización (últimos 30 días)
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 comentario
dpb
dpb el 10 de Ag. de 2022
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.

Iniciar sesión para comentar.

Respuesta aceptada

Bruno Luong
Bruno Luong el 10 de Ag. de 2022
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

Más respuestas (1)

Matt J
Matt J el 10 de Ag. de 2022
Editada: Matt J el 10 de Ag. de 2022
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 comentarios
dpb
dpb el 10 de Ag. de 2022
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 el 10 de Ag. de 2022
Editada: Matt J el 10 de Ag. de 2022
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by