Run function for paired data?

Hi,
Let's say I have a 10x10 matrix A. I wish to run each unique pair of elements from that matrix (e.g. (1,1),(1,2),...,(1,10) - not to repeat (2,1) for instance) in a function that I have. Any ideas how this can be possible?
Thanks!

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 28 de En. de 2015

0 votos

Fred - if you just want to loop over each unique pair of elements in the matrix, then consider doing something like
% assume A is 2D
[r,c] = size(A);
for m=1:r
for n=m:c
% do something with pair (m,n)
end
end
Try the above and see what happens!

2 comentarios

Fred John
Fred John el 29 de En. de 2015
Thanks. But would it be:
for m=1:r
for n=1:r
end
end
to loop over EVERY pair? And how would I write the output matrix? Something like this? :
outputm(m,n)=myfunction(a,b,c) % function and inputs
end
Geoff Hayes
Geoff Hayes el 30 de En. de 2015
Yes, if you assume that the matrix is square and you want loop over each pair (and not the unique ones) then you can do as above (though use c for the number of columns for the case where your matrix is not square). And yes, you can write your output matrix as described above (consider pre-sizing it since you know the dimensions).

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 28 de En. de 2015

0 votos

To get your pair indices:
maxpair = 10; %? a 10x10 matrix has 100 elements.
indices = [repmat([1:maxpair]', 1, 2); nchoosek(1:maxpair, 2)]
You can then use each row of indices as indices into your matrix:
m = randi(1000, 10, 10); %for example
maxpair = numel(m);
indices = [repmat([1:maxpair]', 1, 2); nchoosek(1:maxpair, 2)];
pairs = cellfun(@(row) m(row), num2cell(indices, 2), 'UniformOutput', false) %is this what you want?

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 28 de En. de 2015

Comentada:

el 30 de En. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by