fast way to to change the data in vector

3 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Orion
Orion il 23 Gen 2015
Modificato: Orion il 23 Gen 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.

Più risposte (1)

Stephen23
Stephen23 il 23 Gen 2015
Modificato: Stephen23 il 25 Gen 2015
You can use cumsum to generate the required indices. Copy and place the following code in a script:
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...

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by