Separate correctly values in array
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ana Gabriela Guedes
am 17 Apr. 2021
Bearbeitet: Jan
am 17 Apr. 2021
Hi!
I have 2 vectors: A = [7.046, 15.66, 24.16, 31.476, 39.42, 62.86, 69.83, 91.326, 98.586,106.672, 114.722] corresponds to the instants when some event A occured and
B = 0.53, 1.25, 2.01, 2.78, 3.51, 4.25, 4.96, 5.78, 6.55, 7.26, 7.98, 8.76, 9.54, 10.32,11.08, 11.77, 12.43, 13.68, 14.77, 15.57, 16.31. 17.08, 17.92, 18.72, 19.5, 20.23, 20.9, 21.74, 22.55, 23.36, 24.17, 24.9, 25.68] that corresponds to the instants in which event B is happening.
I want to separate the difference between each B value occuring before and after each event_A and save that values in separate vectors maybe.
For example I would have [B(2)-B(1) B(3)-B(2) ... B(9) - B(8)] (since B(9) = 6.55 < A(1)= 7,046). Then, I would save this vector in a cell array(dont know if there's a better way) and start calculating the differences after A(1) and before A(2): [B(10)-B(9) ... B(20) - B(19)] (since B(20) = 15.57 < A(2) = 15.66) and do this until A(end).
I tried to do this but the cell array always keeps the differences between all B values since B(1) until the last B<A(i) instead of only the intervals I want.
How can I correct the following code to do what I want?
A = [7.046, 15.66, 24.16, 31.476, 39.42, 62.86, 69.83, 91.326, 98.586,106.672, 114.722];
B = 0.53, 1.25, 2.01, 2.78, 3.51, 4.25, 4.96, 5.78, 6.55, 7.26, 7.98, 8.76, 9.54, 10.32,11.08, 11.77, 12.43, 13.68, 14.77, 15.57, 16.31. 17.08, 17.92, 18.72, 19.5, 20.23, 20.9, 21.74, 22.55, 23.36, 24.17, 24.9, 25.68];
result = {};
dif_vector = [];
for i = 1:length(A)
for j = 1:(length(B))-1
if i == 1
if B(j+1) < A(1)
dif = B(j+1)-B(j);
dif_vector= [dif_vector dif];
end
else
if (B(j) > A(i-1) && B(j+1) < A(i))
dif = B(j+1)-B(j);
dif_vector= [dif_vector dif];
end
end
end
result = [result dif_vector];
end
0 Kommentare
Akzeptierte Antwort
Jan
am 17 Apr. 2021
Bearbeitet: Jan
am 17 Apr. 2021
A = [7.046, 15.66, 24.16, 31.476, 39.42, 62.86, 69.83, 91.326, 98.586,106.672, 114.722];
B = [0.53, 1.25, 2.01, 2.78, 3.51, 4.25, 4.96, 5.78, 6.55, 7.26, 7.98, 8.76, ...
9.54, 10.32,11.08, 11.77, 12.43, 13.68, 14.77, 15.57, 16.31, 17.08, ...
17.92, 18.72, 19.5, 20.23, 20.9, 21.74, 22.55, 23.36, 24.17, 24.9, 25.68];
nResult = find(A > B(end), 1); % or: numel(A)
result = cell(1, nResult);
iB1 = 1;
for iA = 1:nResult
iB2 = find(B < A(iA), 1, 'last');
result{iA} = diff(B(iB1:iB2));
iB1 = iB2 + 1;
end
Alternatively:
[~, idx] = sort([B, A]);
wasA = (idx > numel(B));
v = cumsum(wasA) + 1;
result = splitapply(@(x) {diff(x)}, B, v(~wasA))
0 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!