How to get each pair of of row of a matrix to pass into a function?

5 Ansichten (letzte 30 Tage)
Hello Friends,
I have a matrix A of size N x M. I want to get all possible pair of rows, pass them into a function, and get the N x N matrix as output. To be more precise, here is an example of what I want to do:
Example:
Let, A = [1 2; 3 4; 5 6];
Possible row pairs are: {row1, row1}, {row1, row2}, {row1, row3}, {row2, row1}, {row2, row2}, {row2, row3}, {row3, row1}, {row3, row2}, {row3, row3}.
So output will be a 3 x 3 matrix after employing the following steps:
Step-1 For each pair(i,j) or row above
Step-2 function1 = sum(row_i); and function-2 = product(row_j);
Step-3 function3 = sqrt(function1, function2);
Step-4 go to Step-1 and repeat for each pair.
Output Matrix = [f3 f3 f3; f3 f3 f3; f3 f3 f3];
I will appreciate any advice.

Akzeptierte Antwort

Star Strider
Star Strider am 23 Okt. 2015
Bearbeitet: Star Strider am 23 Okt. 2015
This seems to approximate what your Question specifies:
A = [1 2; 3 4; 5 6];
nk = [];
for k1 = 1:size(A,1)
for k2 = 1:size(A,1)
nk = [nk; k1 k2];
end
end
for k1 = 1:size(nk,1)
f1(k1) = sum(A(nk(k1,1),:));
f2(k1) = prod(A(nk(k1,2),:));
f3(k1) = f1(k1).^2 + f2(k1).^2; % Best Guess At: ‘square(function1, function2)’
end
OutputMatrix = reshape(f3, [], 3);
The ‘nk’ variable begins as the combinations of the row numbers taken two at a time. It then loops through, calculating the various function values. You will probeably want to re-define ‘f3’, since I am not clear on your description of it.
EDIT — Added ‘OutputMatrix’, minor recalculation of ‘nk’.
  1 Kommentar
Star Strider
Star Strider am 23 Okt. 2015
My pleasure.
I forgot that you want the rows duplicated, so I added a repmat call to ‘nk’ to accommodate them. The edited code now includes all combinations of them.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

the cyclist
the cyclist am 23 Okt. 2015
I didn't understand Step 3, but this code will do the parts up to there:
A = [1 2; 3 4; 5 6];
[M,N] = size(A);
for m1 = 1:M
row1 = A(m1,:);
s = sum(row1);
for m2 = 1:M
row2 = A(m2,:);
p = prod(row2);
end
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by