fast way to to change the data in vector
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Orion
on 23 Jan 2015
Edited: Orion
on 23 Jan 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 Comments
More Answers (1)
Stephen23
on 23 Jan 2015
Edited: Stephen23
on 25 Jan 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 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!