Info

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

How to operate on different rows of the same matrix?

1 view (last 30 days)
Marco Boesso
Marco Boesso on 28 Oct 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
Good morning folks, I need your help to figure out a possible solution for my issue. I can't find a way out.
Let's consider this matrix A:
1 4 -2 0
2 0 -2 0
3 0 -3 0
4 2 -2 0
I want to operate on the rows, in order to do some operations. Let's stick, for easiness' sake, to this problem: I want to pair the first elements of two different rows. I.e.:
[1, 2]; [1, 3]; [1, 4]; [2, 3]; [2, 4]; [3, 4]
so, it's the first row with the second, the first with the third, the first with the fourth, the second with the third, the second with the fourth, so on...
I had the job done with nested for cycles, but... my supervisor wants me to use a different solution. I need help as I can't find a way out but I desperately need this!
  8 Comments
Rik
Rik on 28 Oct 2020
You can fairly easily convert what you have to either style in my comment. I don't see why you would need to do manual work, that doesn't sound like the Matlab way.

Answers (1)

Sudhakar Shinde
Sudhakar Shinde on 28 Oct 2020
Try this:
[A(1,1) A(2,1)] %[1 2]
[A(1,1) A(3,1)] %[1 3]
[A(1,1) A(4,1)] %[1 4]
[A(2,1) A(3,1)] %[2 3]
[A(2,1) A(4,1)] %[2 4]
[A(3,1) A(4,1)] %[3 4]
  5 Comments
Rik
Rik on 28 Oct 2020
Or you don't use a nested loop with a dynamically exanding variable:
B=nchoosek(1:size(A,1),2);
B=mat2cell(B,ones(size(B,1),1),2);

Community Treasure Hunt

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

Start Hunting!