How to create an N-ary array

조회 수: 4 (최근 30일)
David Cyncynates
David Cyncynates 2020년 12월 18일
댓글: Stephen23 2025년 8월 1일
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
David Cyncynates
David Cyncynates 2020년 12월 18일
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 2020년 12월 18일
편집: James Tursa 2020년 12월 18일
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.

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

답변 (2개)

Stephen23
Stephen23 2020년 12월 18일
편집: Stephen23 2025년 7월 27일
N = 4;
K = 3;
C = cell(1,K);
[C{:}] = ndgrid(1:N);
M = reshape(cat(K+1,C{:}),[],K)
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 3 3 1 4 3 1 1 4 1 2 4 1 3 4 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
How it works:
As James Tursa pointed out, you could quickly run out of memory for large values of K.
  댓글 수: 4
Paul
Paul 2025년 7월 27일
Would you mind posting back here the outcome of the bug report? Thx.
Stephen23
Stephen23 2025년 8월 1일
@Paul: TMW confirmed that it is a bug, which apparently arose due to changes made in R2020b. It will get fixed in a future release.

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


Bruno Luong
Bruno Luong 2020년 12월 19일
N=3
K=5
[~,A] = ismember(dec2base(0:N^K-1,N),['0':'9' 'A':'Z']);
A = A-1

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by