2017-01-23 7 views
1

출력으로 1D 배열과 결과가있는 파라 메트릭 분석에서 데이터를 후행 처리해야합니다. 이 1D 배열을 조사한 매개 변수의 차원 (올바른 순서로), 을 갖는 다차원 행렬로 다시 만들고 싶습니다. 그 차원은과 다를 수 있습니다.잠재적 인 매우 큰 1 차원 배열을 가변 치수의 다차원 행렬로 바꿈

for 루프를 기반으로하는 함수를 만들 수는 있지만 매우 큰 배열에서는 RAM이 부족합니다. 나는 이것이 이것이 가장 똑똑한 방법이 아니라는 것을 완벽하게 알고 있습니다. 큰 배열을 조작하고 내 기능과 똑같은 일을하는 똑똑한 방법이 있는지 궁금합니다. 요소 수백만 예로서

function [Tensor, n_dimensions]=reshape_array(Data,ndim) 

n_dimensions=length(ndim); 
n_elements=prod(ndim); 

reshape_string=[]; 
for i=n_dimensions:-1:1 
    if i==1 
    reshape_string=strcat(reshape_string, ' ndim(', num2str(i) , ')])'); 
    elseif i== n_dimensions 
    reshape_string=strcat(reshape_string, ' [ndim(', num2str(i) , ')'); 
    else 
    reshape_string=strcat(reshape_string, ' ndim(', num2str(i) , ') '); 
    end 

end 

invert_string=[]; 
for i=1:n_dimensions 
    if i==1 
    invert_string=strcat(invert_string, 'ndim(', num2str(i) , '),'); 
    elseif i== n_dimensions 
    invert_string=strcat(invert_string, ' ndim(', num2str(i) , ')'); 
    else 
    invert_string=strcat(invert_string, ' ndim(', num2str(i) , '),'); 
    end 

end 

reshape_statement=strcat('reshape(Data,',reshape_string); 
invert_statement=strcat('zeros(',invert_string,');'); 

Tens1=eval(reshape_statement); 
Tens2=eval(invert_statement); 

nLoops=length(ndim); 
str = ''; 
str_dim_tens=''; 
str_dim_indeces=''; 
for i=1:nLoops 
    str = strcat(sprintf('%s \n for i%d=1:',str,i), sprintf('%d',ndim(i))); 
    if i<nLoops 
    str_dim_tens=strcat(str_dim_tens,'i',num2str(i),','); 
    else 
    str_dim_tens=strcat(str_dim_tens,'i',num2str(i)); 
    end 
end 

for i=nLoops:-1:1 
    if i~=1 
    str_dim_indeces=strcat(str_dim_indeces,'i',num2str(i),','); 
    else 
    str_dim_indeces=strcat(str_dim_indeces,'i',num2str(i)); 
    end 
end 

str = strcat(sprintf('%s \n Tens2(%s)=Tens1(%s);',str,str_dim_tens,str_dim_indeces)); 

for i=1:nLoops 
    str = sprintf('%s \n end',str); 
end 

eval(str) 

Tensor=Tens2; 

end 

,

ndim=[2 3]; 
Data=1:2*3 
[Tensor, n_dimensions]=reshape_array(Data,ndim); 

n_dimensions = 

    2 

Tensor = 

    1  2  3 
    4  5  6 

I보다 치수 일 것이다 (예를 들어, 최소 4) 및 데이터 어레이. 예를 들면 M (101010300000) 일 수 있습니다.이 때문에 최소한의 계산 방식으로 비용이 많이 드는 방법을 찾고있었습니다.

도움 주셔서 감사합니다.

답변

5

코드에서 Matlab의 column-major 기본값의 반대 인 차원 순서를 사용하여 재구성 된 배열의 요소를 채우고 싶습니다. 즉, 마지막 dimenson부터 시작하여 두 번째 마지막 등으로부터 시작합니다.

이 순서는 역순으로 배열을 바꾸고 (reshape을 사용하여) 배열을 다시 배열하여 permute).

n_dimensions = numel(ndim); 
Tensor = reshape(Data, ndim(end:-1:1)); % reshape with dimensions in reverse order 
Tensor = permute(Tensor, n_dimensions:-1:1); % reverse back order of dimensions 
+1

세포가 실제로 필요한가요? 모양을 변형하지 않고 배열을 모양 입력으로 허용합니까? –

+0

좋은 지적! 나는 그렇게 생각한다. 나는 그것을 나중에 편집 할 것이고, 이제 나는 달려야한다. 또는 직접 편집하십시오 :-) –

+1

똑똑하고 빠르며 더 짧습니다. 감사! –