是否有必要根据维度矩阵制作一个for循环来制作一个matricies?

时间:2015-07-26 15:56:51

标签: matlab

我想在给定大小矩阵的情况下生成所有1个矩阵的集合(在此示例中为dimensions),但我一直很难使维度矩阵返回{{{{ 1}}可以使用。

我的第一直觉是:ones

我将此(错误地)读作dimensions(:,:)

但这似乎不起作用 - 有没有办法使用维度来生成大小向量矩阵?

我很想使用循环来迭代,因为i = 1到3 return a matrix of size vectors [x,y],但我想知道这是否是唯一的方法。

代码:

dimensions(i,:)

编辑:输出:

的输出
clear;

%3x2
dimensions = [32,40; %32x40 box of ones
          20, 30; %20x30 box of ones
          60, 10; %60x10 box of ones
          ];



Onesboxes = ones(dimensions(1,:));

%this works, but I really want OnesBoxes to be an array such that:

%OnesBoxes(1) = 32x40 box of ones
%OnesBoxes(2) = 20x30 box of ones
%OnesBoxes(3) = 60x10 box of ones

% if I try:
OnesBoxes = ones(dimensions); 

%Error using ones: Size vector should be a row vector with real elements.

%what I want to do is pass in sizes as rows in dimensions

%passing in the size of the ones array as a single vector works:
%onessize dimensions: 1x2
onessize = [4,2];

%tTestOnes dimensions: 4x2
tTestOnes = ones(onessize);

%making dimensions a 2x3 matrix instead doesn't seem to make a difference
%(I was thinking that maybe matlab thinks of matricies as an array of
%columns instead of arrays of rows?)
    %dimensions2 = [32,20,60; 40,30,10];

    %tOnesBoxes2 = ones(dimensions2);

是所有1的4x2数组

的输出
onessize = [4,2];

%tTestOnes dimensions: 4x2
tTestOnes = ones(onessize);

是一个32x40的全部数组

的输出
dimensions = [32,40; %32x40 box of ones
          20, 30; %20x30 box of ones
          60, 10; %60x10 box of ones
          ];

Onesboxes = ones(dimensions(1,:));

是错误

  

使用1时出错大小向量应该是带有real的行向量   元件。

2 个答案:

答案 0 :(得分:1)

如果你对for循环没问题,我能想到的最简单的方法是:

dimensions = [32,40; %32x40 box of ones
              20, 30; %20x30 box of ones
              60, 10; %60x10 box of ones
             ];
for i=1:size(dimensions,1)
    OnesBoxes{i}=ones(dimensions(i,:));
end

这将像你想要的那样创建OnesBoxes

OnesBoxes{1}% = 32x40 box of ones
OnesBoxes{2}% = 20x30 box of ones
OnesBoxes{3}% = 60x10 box of ones

答案 1 :(得分:0)

您需要传递ones一个定义矩阵大小的向量。如果您需要多个矩阵,则需要多次调用ones。要收集所有生成的矩阵,您需要一个单元格数组,因为矩阵具有不同的大小。

您可以使用for循环,arrayfuncellfun来完成此操作。我在这里使用后者:

dimensions = [ 2 3;
               4 5 ]; %// input data. Each row defines a matrix size
dimCell = mat2cell(dimensions, ones(1,size(dimensions,1)), size(dimensions,2));
    %// split each row into a cell, ready to be used as input for `cellfun`
result = cellfun(@(x) ones(x), dimCell, 'uniformoutput', false);

这给出了所需矩阵的单元阵列。在示例中,

>>  result
result = 
    [2x3 double]
    [4x5 double]
>> celldisp(result)
result{1} =
     1     1     1
     1     1     1
result{2} =
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1