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

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

Answers (1)

DGM
DGM on 12 May 2021
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
Cameron Kirk
Cameron Kirk on 13 May 2021
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.'
DGM
DGM on 13 May 2021
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.

Community Treasure Hunt

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

Start Hunting!