How to create a loop function within the same array?

조회 수: 1 (최근 30일)
Jorge Rodriguez
Jorge Rodriguez 2017년 6월 27일
댓글: Jorge Rodriguez 2017년 6월 27일
Hello, I'm trying to operate with an array of over 100000 data points (i.e. "k"). I have one array with the ID (i.e."ID") of the point and a second array with the data (i.e. "E")corresponding to each specific ID. The idea is that once an ID is equal to the previous value then it would to an operation that subtracts values from the array "E" creating the array "DE"; else, if the ID is different from previous value then "DE" is Zero.
DE = zeros(k,1);
for i=2:k
if ID(i,1)==ID(i-1,1)
DE(i,1)=(E(i,1)-E(i-1,1))*1000;
else
DE(i,1)=0;
end
end
The problem that I have is that the array "DE" becomes a column of zeros of size k.

답변 (1개)

James Tursa
James Tursa 2017년 6월 27일
편집: James Tursa 2017년 6월 27일
A vectorized version (assuming I understand your dimensions correctly):
diffI = [1;diff(ID(:,1))];
diffE = [0;diff(E(:,1))]*1000;
DE = zeros(k,1);
x = diffI==0;
DE(x) = diffE(x);
  댓글 수: 1
Jorge Rodriguez
Jorge Rodriguez 2017년 6월 27일
Thanks James for that quick response. I'm not a frequent user of Matlab. Basically a beginner in this area. I see that the problem of using diff function is that it works on numerical values only. Sorry, I did not clarify the type of vectors I'm using and it seems to be very relevant. All arrays (i.e. DE, ID, E) are one-dimensional vectors, and the cells of the ID vector is with characters.
For example:
ID=[A;A;A;A;A;A;B;B;B;B;B;B;B;C;C;C;C;C;C;.....;Z;Z;Z;Z]
E=[12.45667745;34,45457788899;4.675474;.....;12.4534535]
I need that when ID changes from A to B and B to C and so on then the difference in E restarts in zero. Also, I need to keep the same size of the vectors and using the "diff" it reduces by one the vector.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by