一次为MATLAB中的单元格数组分配不同的值 [英] Assign different values to cell arrays in MATLAB at once

查看:148
本文介绍了一次为MATLAB中的单元格数组分配不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在MATLAB中创建一个单元格数组的帮助,其中每个单元格都是大小不同的数组.例如,假设我有这个简单的数组和值:

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;

单元格数组C必须这样创建:

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)

但是没有用.

推荐答案

cellfun期望单元格数组作为函数的输入.您有一个数字数组,因此请使用 arrayfun .您也不会在数组中的每个元素上输出标量,因此您需要将UniformOutput标志设置为0.最后,使用colon运算符执行所需的操作,而不是矩阵乘法.不幸的是,输出将是单元格的行向量,因此,如果您绝对需要列向量(如您在帖子中所显示的那样),请转置输出:

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).';

请注意,声明为arrayfun的第一个输入的匿名函数具有词法作用域,这意味着在匿名函数声明之前在工作区中可见的任何变量都是可见的.您可以只在函数内部访问该变量,而不必手动将其作为单独的输入输入arrayfun.

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.

我们现在得到:

>> 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

这篇关于一次为MATLAB中的单元格数组分配不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆