简体   繁体   English

一次为MATLAB中的单元格数组分配不同的值

[英]Assign different values to cell arrays in MATLAB at once

I need help on creating a cell array in MATLAB where each cell is an array of different sizes. 我需要在MATLAB中创建一个单元格数组的帮助,其中每个单元格都是大小不同的数组。 For example, let's assume I have this simple array and the value: 例如,假设我有这个简单的数组和值:

A = [5 3 8 7 0 4 1];
B = 10;

The cell array C must be created such that: 单元格C必须创建为:

C = 
[10 20 30 40 50]
[10 20 30]
[10 20 30 40 50 60 70 80]
[10 20 30 40 50 60 70]
[Empty matrix 1x0]
[10 20 30 40]
[10]

Is it possible to do that in one operation only? 只能一次执行此操作吗? I have tried: 我努力了:

C = cellfun(@(a,b)b*ones(1,a), A,B)

but it did not work. 但它没有用。

cellfun expects a cell array as the input into the function. cellfun希望将单元格数组作为函数的输入。 You have a numeric array so use arrayfun instead. 您有一个数字数组,请改用arrayfun You are also not outputting a scalar per element in the array so you need to set the UniformOutput flag to 0. Finally, use the colon operator to do what you need instead of matrix multiplication. 您也不会在数组中为每个元素输出标量,因此您需要将UniformOutput标志设置为0。最后,使用colon运算符执行所需的操作,而不是矩阵乘法。 The output will unfortunately be a row vector of cells so if you absolutely need a column vector such as what you have shown in your post, transpose the output: 不幸的是,输出将是单元格的行向量,因此,如果您绝对需要列向量(如帖子中显示的内容),请转置输出:

A = [5 3 8 7 0 4 1];
B = 10;
C = arrayfun(@(x) B*(1:x), A, 'UniformOutput', 0).';

Take note that the anonymous function declared as the first input into arrayfun has lexical scope, meaning that any variables that were visible in the workspace before the anonymous function declaration is visible. 请注意,声明为arrayfun的第一个输入的匿名函数具有词法作用域,这意味着在匿名函数声明之前在工作空间中可见的任何变量都是可见的。 You can just access that variable inside your function instead of having to manually feed it into arrayfun as a separate input. 您可以只在函数中访问该变量,而不必手动将其作为单独的输入输入到arrayfun中。

We now get: 现在我们得到:

>> format compact
>> celldisp(C)
C{1} =
    10    20    30    40    50
C{2} =
    10    20    30
C{3} =
    10    20    30    40    50    60    70    80
C{4} =
    10    20    30    40    50    60    70
C{5} =
     []
C{6} =
    10    20    30    40
C{7} =
    10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM