How to create an N-ary array

2 visualizaciones (últimos 30 días)
David Cyncynates
David Cyncynates el 18 de Dic. de 2020
Respondida: Bruno Luong el 19 de Dic. de 2020
Suppose I have K variables, each of which can take the values 1 through N. I want to create a table such that each column corresponds to the Kth variable, and each row corresponds to a particular combination. This table will be N^K entries long and K entries wide. One way to do this would be, for example
[V1 V2 ... VK] = ngrid(1:N,1:N,...,1:N)
V = [V1 V2 ... VK]
However, this clearly does not generalize nicely to variable N. Is there a simple way to extend this code so it works for different K?
  8 comentarios
David Cyncynates
David Cyncynates el 18 de Dic. de 2020
Here's an example of what I was trying to write. Perhaps I'll just stick with this:
N = 4;
K = 3;
V = zeros(K,N^K);
ii = 0 : N^K - 1;
for jj = 1 : K
V(jj,:) = floor((mod(ii,N^jj))/N^(jj-1));
end
James Tursa
James Tursa el 18 de Dic. de 2020
Editada: James Tursa el 18 de Dic. de 2020
OK, got it. Looks like you are basically counting in base N with K digits. How large can K and N be? This could easily eat all your memory if they are too large.

Iniciar sesión para comentar.

Respuestas (2)

Stephen23
Stephen23 el 18 de Dic. de 2020
Editada: Stephen23 el 19 de Dic. de 2020
N = 4;
K = 3;
C = cell(1,K);
[C{:}] = ndgrid(1:N);
C = cellfun(@(m)m(:),C,'uni',0);
M = [C{:}]
M = 64×3
1 1 1 2 1 1 3 1 1 4 1 1 1 2 1 2 2 1 3 2 1 4 2 1 1 3 1 2 3 1
... lots more rows here not shown
How it works:
As James Tursa pointed out, you could quickly run out of memory for large values of K.

Bruno Luong
Bruno Luong el 19 de Dic. de 2020
N=3
K=5
[~,A] = ismember(dec2base(0:N^K-1,N),['0':'9' 'A':'Z']);
A = A-1

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by