accepting values into an array, then accepting new values by shifting left
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Michael Scott
el 10 de Feb. de 2018
Comentada: Michael Scott
el 11 de Abr. de 2018
I am calling a function in a different m file. I want this function to write newValues into an array. After 7 entries, the newValues need to be added to the end of the array and then shifted left in order to keep the values in order. Example: values accepted in the array are [1 2 3 4 5 6 7]. The new value is 8 which makes the array have values [2 3 4 5 6 7 8]. This is what I have so far....
function arrayWithLatestValues = fn_updateArray(newValue)
persistent A;
A = [A(2:end) newValue];
arrayWithLatestValues = A;
end
this is my output im getting:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 comentarios
Respuesta aceptada
possibility
el 10 de Feb. de 2018
Editada: possibility
el 10 de Feb. de 2018
I'm guessing it is because of the persistent statement. Quote from the statement explanation:
" If the persistent variable does not exist the first time you issue the persistent statement, it will be initialized to the empty matrix."
If you have the vector as an input to the function, I believe the problem will be solved.
function arrayWithLatestValues = fn_updateArray(newValue,A)
A = [A(2:end) newValue];
arrayWithLatestValues = A;
end
Más respuestas (1)
Stephen23
el 10 de Feb. de 2018
Editada: Stephen23
el 10 de Feb. de 2018
function outVec = fn_updateArray(newValue)
persistent newVec;
newVec = [newVec(max(1,end-5):end),newValue];
outVec = newVec;
end
and tested:
>> fn_updateArray(1)
ans = 1
>> fn_updateArray(2)
ans =
1 2
>> fn_updateArray(3)
ans =
1 2 3
>> fn_updateArray(4)
ans =
1 2 3 4
>> fn_updateArray(5)
ans =
1 2 3 4 5
>> fn_updateArray(6)
ans =
1 2 3 4 5 6
>> fn_updateArray(7)
ans =
1 2 3 4 5 6 7
>> fn_updateArray(8)
ans =
2 3 4 5 6 7 8
>> fn_updateArray(9)
ans =
3 4 5 6 7 8 9
>>
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!