Info

This question is closed. Reopen it to edit or answer.

Calculating value from two column with a cell string

1 view (last 30 days)
SS
SS on 17 Oct 2014
Closed: MATLAB Answer Bot on 20 Aug 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 Comment
Guillaume
Guillaume on 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

Answers (1)

Guillaume
Guillaume on 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))]

This question is closed.

Community Treasure Hunt

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

Start Hunting!