fast way to to change the data in vector
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Brasco , D.
el 23 de En. de 2015
I want to change specific part of a data in vector and i want it to be very fast and simple.
Here is an example:
Let say i have vector " A=[2 5 8 10 14 16 5 8 9 12] " which represents a property of a physical system.
Let say, in reality, values of A can't be more than 10. i want to change the values that are bigger than 10 and make them equal to the previous column's. (the first column is not important for me but if you have solution including that, it will be appriciated)
% code
for i=2:1:length(A);
if A(i)>10;
A(i)=A(i-1);
end
end
this code works fine but i have to do this for more than 100 vector that have more than 500k rows.
and this takes to much time for matlab.
Is there any way to do this faster?
0 comentarios
Respuesta aceptada
Orion
el 23 de En. de 2015
Editada: Orion
el 23 de En. de 2015
One way to go faster : just loop on the values superior to 10.
A = [2 5 8 10 14 16 5 8 9 12];
indsup10 = find(A(2:end)>10);
if ~isempty(indsup10)
for i=1:length(indsup10);
if A(indsup10(i)+1)>10;
A(indsup10(i)+1)=A(indsup10(i));
end
end
end
the execution speed just depends of the number of elements superior to your threshold.
0 comentarios
Más respuestas (1)
Stephen23
el 23 de En. de 2015
Editada: Stephen23
el 25 de En. de 2015
A = [12,15,8,10,14,16,5,8,9,12,20,1,2,3,11,5];
%A = [2,5,8,10,14,16,5,8,9,12,20,1,2,3,11,5];
B = A>10;
C = [false,diff(B)<0];
D = cumsum(B);
E = [0,D(C),0];
F = cumsum(~B) + E(1+cumsum(C));
F(F==0) = 1+E(2);
G = A(F);
[A;G]
When I run this script I get:
ans =
12 15 8 10 14 16 5 8 9 12 20 1 2 3 11 5
8 8 8 10 10 10 5 8 9 9 9 1 2 3 3 5
This also replaces all leading >10 values with the first <=10 value. Although a well designed loop is likely to be faster than this code...
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays 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!