How to get each pair of of row of a matrix to pass into a function?
5 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!