How to create a loop function within the same array?

1 view (last 30 days)
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.

Answers (1)

James Tursa
James Tursa on 27 Jun 2017
Edited: James Tursa on 27 Jun 2017
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 Comment
Jorge Rodriguez
Jorge Rodriguez on 27 Jun 2017
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!