How can I subtract columns for each row by using a for loop
Show older comments
Hi,
I have a matrix like this:
[1.011 1.004 1.054
1.008 0.998 1.042
0.984 0.988 1.024
1.026 1.006 1.016
1.000 0.996 0.977]
I would like to subtract each column for each row and store these results in a new matrix. How can I do this?
Thanks!
2 Comments
Joseph Cheng
on 29 Sep 2014
can you expand on what you mean by subtract each column for each row? I do not understand what you're subtracting with.
Jimmy
on 29 Sep 2014
Accepted Answer
More Answers (3)
Joseph Cheng
on 29 Sep 2014
Edited: Joseph Cheng
on 29 Sep 2014
you can use combnk() or nchoosek to determine the combination of column subtraction and perform a for loop for each combination.
X = randi(10,4,3);
combin = combnk(1:size(X,2),2);
for ind = 1:size(X,2)
newX(:,ind) = X(:,combin(ind,1))-X(:,combin(ind,2));
end
Guillaume
on 29 Sep 2014
Use nchoosek to get all possible combinations of columns, and use that to calculate your differences:
m = [1.011 1.004 1.054
1.008 0.998 1.042
0.984 0.988 1.024
1.026 1.006 1.016
1.000 0.996 0.977];
colcomb = nchoosek(1:size(m, 2), 2);
coldiff = zeros(size(m, 1), size(colcomb, 1));
for comb = 1:size(colcomb, 1)
coldiff(:, comb) = diff(m(:, colcomb(comb, :)), 1, 2);
end
7 Comments
Jimmy
on 29 Sep 2014
Guillaume
on 29 Sep 2014
Not in a matrix obviously, since it can only contain numbers. You could create a cell array of column names
colnames = cell(size(colcomb, 1));
for comb = 1:size(colcomb, 1)
colnames{comb} = sprintf('%d-%d', colcomb(comb, 2), colcomb(comb, 1));
end
Note that the difference calculated are 2-1, 3-1, 3-2, and I've represented that in the names.
Jimmy
on 29 Sep 2014
dpb
on 29 Sep 2014
For what working definition of small? But, basic idea is one of two choices...
a) go ahead and generate all pairs and then compute the comparison statistic and choose the N smallest of those, or,
b) compute each pair and the statistic at same time; after N replace the largest of those kept with the last if new is less; update the maxValue comparison value.
Jimmy
on 30 Sep 2014
Andrei Bobrov
on 30 Sep 2014
Edited: Andrei Bobrov
on 30 Sep 2014
X = [1.011 1.004 1.054
1.008 0.998 1.042
0.984 0.988 1.024
1.026 1.006 1.016
1.000 0.996 0.977];
n = nchoosek(1:size(X,2),2);
out = squeeze(diff(reshape(X(:,n'),[],2,3),1,2));
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!