Calculate table column with a loop

2 views (last 30 days)
Hi Matlabfriends,
I have a large table with data (120 column and 200 rows). I have to subtract column 2 (all rows) from column 1 (all rows),
column 3 (all rows) from column 2 (all rows), and so on, until column 120 (all rows). Can I solve this with a loop, how?
Thanks!
Here is my try (note: I'm an absolutley beginner):
for i=1:120
variable1(i,1:120)=table(i,1:2:119) - table(i,2:2:120);
end

Accepted Answer

Guillaume
Guillaume on 6 Nov 2019
Edited: Guillaume on 6 Nov 2019
As usual with matlab, it's simpler without a loop
result = diff(table2array(yourtable), [], 2); %difference between consecutive columns
Note that you may be better off using a matrix rather than a table for storing your original data.
edit: the above assumes that you're actually storing your data in a matlab table. But judging by your syntax you may actually be storing your data in matrix, in which case:
result = diff(yourmatrix, [], 2);
Whether a matrix or table, don't use table as a variable name, since it will prevent you from constructing tables.

More Answers (1)

Takumi
Takumi on 6 Nov 2019
table = rand(200,120); %sample data
[row,col] = size(table);
for i = 1:col-1
variable1(:,i) = table(:,i+1) - table(:,i);
end

Products

Community Treasure Hunt

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

Start Hunting!