Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Calculating value from two column with a cell string

1 vue (au cours des 30 derniers jours)
SS
SS le 17 Oct 2014
Clôturé : MATLAB Answer Bot le 20 Août 2021
Hi,
I have three columns like this way. here a is cell string, 2nd and 3rd column are numbers
  • 1st column: a,a,a....
  • 2nd column:102, 135.....and 3rd column:103,136.......
  • a 102 103
  • a 135 136
  • a 157 160
  • b 189 191
  • b 201 202
  • a 222 223
  • a 245 250
  • b 290 292
I want to write a formula, which show the total duration of seconds of a and b.
For example: here total duration of a is = (160-102) + (250-222) = 86 seconds.
Please suggest me how to do it.
Thanks
  1 commentaire
Guillaume
Guillaume le 17 Oct 2014
It would make more sense to me (and easier to code) if duration of a was either:
  1. 250-102
  2. 103-102 + 136-135 + 160-157 + 223-222 + 250-245

Réponses (1)

Guillaume
Guillaume le 17 Oct 2014
Assuming that the string is a single letter and your cell array is defined like this:
c={'a' 102 103
'a' 135 136
'a' 157 160
'b' 189 191
'b' 201 202
'a' 222 223
'a' 245 250
'b' 290 292}
Then the following will do what you want:
starts = find(diff([' ' c{:, 1} ' '])) %starts of intervals + end of last interval
cconcat = [c(starts(1:end-1), [1 2]), c(starts(2:end)-1, 3)] %intervals concatenated
durations = vertcat(cconcat{:, 3}) - vertcat(cconcat{:, 2}) %duration of intervals
[names, ~, idnames] = unique([cconcat{:, 1}]')
fulldurations = [num2cell(names) num2cell(accumarray(idnames, durations))]

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by