Assign different values to cell arrays in MATLAB at once

大憨熊 提交于 2019-12-11 03:38:05

问题


I need help on creating a cell array in MATLAB where each cell is an array of different sizes. 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 = 
[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.


回答1:


cellfun expects a cell array as the input into the function. You have a numeric array so use arrayfun instead. 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. 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. You can just access that variable inside your function instead of having to manually feed it into arrayfun as a separate input.

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


来源:https://stackoverflow.com/questions/39394731/assign-different-values-to-cell-arrays-in-matlab-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!