Subtact one column of a cell array from another and put the result in the 3rd column

Hello,
I've got a cell array (712x2), and I want to substract every value in the second column from every value in the first column, and post the results in column 3. below is an example of what the data looks like. Can anyone please help me? because I am completely stuck, and can't see any information for this online.

1 Comment

Storing lots of datetime scalars is less efficient than having just two datetime vectors.

Sign in to comment.

Answers (1)

I'm going to assume those are all datetime values
% make test array
t1 = datetime('now','Format','HH:mm:ss');
t = t1 + minutes(0:10:135)';
t = [t t+minutes(rand(size(t)))];
C = mat2cell(t,ones(size(t,1),1),[1 1])
D = vertcat(C{:,1})-vertcat(C{:,2}); %find difference
C = [C mat2cell(D,ones(size(D)),1)] % concatenate new column
which gives
C =
14×3 cell array
{[09:58:44]} {[09:59:33]} {[-00:00:48]}
{[10:08:44]} {[10:08:55]} {[-00:00:10]}
{[10:18:44]} {[10:19:37]} {[-00:00:52]}
{[10:28:44]} {[10:28:53]} {[-00:00:08]}
{[10:38:44]} {[10:39:37]} {[-00:00:53]}
{[10:48:44]} {[10:48:46]} {[-00:00:01]}
{[10:58:44]} {[10:59:21]} {[-00:00:37]}
{[11:08:44]} {[11:09:23]} {[-00:00:39]}
{[11:18:44]} {[11:19:25]} {[-00:00:41]}
{[11:28:44]} {[11:29:16]} {[-00:00:32]}
{[11:38:44]} {[11:39:11]} {[-00:00:27]}
{[11:48:44]} {[11:48:52]} {[-00:00:08]}
{[11:58:44]} {[11:59:14]} {[-00:00:30]}
{[12:08:44]} {[12:08:48]} {[-00:00:04]}
If those are datetimes though, you can also just make an array of datetimes without the cell array.
If those are something other than datetimes, you'll have to say what they are.

4 Comments

Thanks so much! With your help I've now managed to get the third column, but it's now a duration. How can I convert it into a double?
You'll have to decide how you want the output represented.
Let's say I have a duration vector D, as in the example. Then
Ds = seconds(D);
would convert it to a numeric vector of seconds. You could also use minutes() or hours() as appropriate for your case.
This is great thanks. The seconds output is exactly what I'm after. I'm now trying to add the result as a column on a struct and I'm getting the error message 'Scalar structure required for this assignment.'
Can you make a simple example of the struct you have (how it's arranged) and how you're trying to do the assignment?

Sign in to comment.

Categories

Asked:

on 12 May 2021

Commented:

DGM
on 13 May 2021

Community Treasure Hunt

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

Start Hunting!