matlab 如何提供要重塑为向量变量的数组的维度?

rekjcdws  于 2022-11-15  发布在  Matlab
关注(0)|答案(1)|浏览(149)

我想在每次迭代中重塑数组G,新维度的形状来自向量(比如)tensorSize。但MatLab重塑命令不接受下面给出的方法,

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

我也曾尝试使用其他替代方案,例如:

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

但它们创建一个字符串,当转换为num时,它们不是逗号分隔的。因此,重塑选项不接受它。
这附近有什么工作吗?

xienkqul

xienkqul1#

感谢下面评论区的@beaker提出了这个解决方案!

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

相关问题