fast way to to change the data in vector
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Orion
2015-1-23
编辑:Orion
2015-1-23
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 个评论
更多回答(1 个)
Stephen23
2015-1-23
编辑:Stephen23
2015-1-25
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!