Save value from overwriting in while loop

4 visualizaciones (últimos 30 días)
mohamed hassan
mohamed hassan el 7 de Mayo de 2020
Comentada: Ameer Hamza el 8 de Mayo de 2020
end
In this while loop I want to save u(end) and u1(end) in a vector but when i Try to do it it becomes problematic. Firslty I know how to do it if it only would been one variable (u), but in m case it is u1 too. For every iteration u1 and u ( last element of those ) gets overwritten so I dont know how to save u and u1 ( last elements) in a vector.
  2 comentarios
Ameer Hamza
Ameer Hamza el 8 de Mayo de 2020
Mohammed Hassan, This forum is for public benefit. Deleting the code in question makes the question meaningless for anyone else. I am restoring the code so that anyone else coming to this form can have a better idea about the original question.
Ameer Hamza
Ameer Hamza el 8 de Mayo de 2020
Text of original Question:
hI
En=50
While d >tollerance
[g u] = main(En,k)
En=En*3;
[g u1] = main(En,k)
d=abs((u(En/3)+1)-u1(En+1));
end
In this while loop I want to save u(end) and u1(end) in a vector but when i Try to do it it becomes problematic. Firslty I know how to do it if it only would been one variable (u), but in m case it is u1 too. For every iteration u1 and u ( last element of those ) gets overwritten so I dont know how to save u and u1 ( last elements) in a vector.

Iniciar sesión para comentar.

Respuestas (1)

Ameer Hamza
Ameer Hamza el 7 de Mayo de 2020
Editada: Ameer Hamza el 7 de Mayo de 2020
The most simplest way is to let the array grow dynamically
En=50
u = [];
u1 = [];
while d >tollerance
[g u(end+1)] = main(En,k)
En=En*3;
[g u1(end+1)] = main(En,k)
d=abs((u(En/3)+1)-u1(En+1));
end
  13 comentarios
Ameer Hamza
Ameer Hamza el 7 de Mayo de 2020
'temp1(end)' means that the last element of the vector temp1. Since you mentioned that main() returns a vector, and you want to keep the last value of that vector. The 'temp1(end)' keeps that last value.
u(end+1) tells the MATLAB to extend the array 'u' and add the new element to the extended location. This makes sure that the last value is not overwritten.
mohamed hassan
mohamed hassan el 7 de Mayo de 2020
Thank you , I just wondering if it's possible to make it more adaptive ? more efficient, because I use the same kinda code twice in the loop?

Iniciar sesión para comentar.

Categorías

Más información sobre Downloads en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by