Home > front end >  How do I provide dimensions of an array to be reshaped as a vector variable?
How do I provide dimensions of an array to be reshaped as a vector variable?

Time:08-30

I want to reshape the array G in every iteration, and the shape for new dimensions are coming from vector (say) tensorSize. But the MATLAB reshape command does not accept the below given method,

tensorSize = [5,6,7,9,3,4];
r=[1,5,25,225,45,9,1];
G1(1) = {randn(1,tensorSize(1),r(2))};
G1(2) = {randn(r(2),tensorSize(2),r(3))};
G1(3) = {randn(r(3),tensorSize(3),r(4))};
G1(4) = {randn(r(4),tensorSize(4),r(5))};
G1(5) = {randn(r(5),tensorSize(5),r(6))};
G1(6) = {randn(r(6),tensorSize(6),1)};

for j = 1:length(tensorSize)-1
    if j == 1
        G = G1(j);
    end
    G = reshape(G,[],r(j 1));
    H = reshape(G1(j 1),r(j 1),[]);
    G = G*H;
    G = reshape(G,tensorSize(1:j 1),[]);
end

I have also tried to use other alternatives like:

str2num(regexprep(num2str(tensorSize(1:j 1),),'\s ',','))
str2num(strjoin(cellstr(tensorSize(1:j 1)),','))

but they create a string and when converted to num, they are not comma separated. So the reshape option does not accept it.

Is there any work around?

CodePudding user response:

Thanks to @beaker in the comment section below, for proposing this solution!

    tensorSize = [5,6,7,9,3,4];
    r=[1,5,25,225,45,9,1];
    G1(1) = {randn(1,tensorSize(1),r(2))};
    G1(2) = {randn(r(2),tensorSize(2),r(3))};
    G1(3) = {randn(r(3),tensorSize(3),r(4))};
    G1(4) = {randn(r(4),tensorSize(4),r(5))};
    G1(5) = {randn(r(5),tensorSize(5),r(6))};
    G1(6) = {randn(r(6),tensorSize(6),1)};
    tensorSizeCell = {zeros(1,length(tensorSize))};

    for i = 1:length(tensorSize)
        tensorSizeCell(i) =  {tensorSize(i)};
    end

    for j = 1:length(tensorSize)-1
        if j == 1
            G = cell2mat(G1(j));
        end
        G = reshape(G,[],r(j 1));
        H = reshape(cell2mat(G1(j 1)),r(j 1),[]);
        G = G*H;
        G = reshape(G,tensorSizeCell{1:j 1},[]);
    end
  • Related