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

조회 수: 3 (최근 30일)
hello_world
hello_world 2015년 10월 23일
편집: Star Strider 2015년 10월 23일
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.

채택된 답변

Star Strider
Star Strider 2015년 10월 23일
편집: Star Strider 2015년 10월 23일
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
Star Strider
Star Strider 2015년 10월 23일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

the cyclist
the cyclist 2015년 10월 23일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by