fast way to to change the data in vector

조회 수: 2 (최근 30일)
Brasco , D.
Brasco , D. 2015년 1월 23일
편집: Stephen23 2015년 1월 25일
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?

채택된 답변

Orion
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.

추가 답변 (1개)

Stephen23
Stephen23 2015년 1월 23일
편집: Stephen23 2015년 1월 25일
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...

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by