如何在Matlab的单元格数组的每个单元格中插入数字? [英] How to insert a number to every cell of a cell array in Matlab?

查看:312
本文介绍了如何在Matlab的单元格数组的每个单元格中插入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的单元格数组:

I have a cell array like this:

    a = {[1 2 3]; [4 5]; [6 7 8 9]};

,并希望在每个单元格的开头插入10,以使其具有以下功能:

and want to insert, for example, 10 to the beginning of every cell to have this:

    >> a{:}

    ans =

        10     1     2     3

    ans =

        10     4     5

    ans =

        10     6     7     8     9

是否可以在没有任何for循环的情况下做到这一点?

Is it possible to do it without any for loop?

推荐答案

您可以使用 CELLFUN :

b = cellfun(@(x)[10 x],a,'UniformOutput',0)


要回答@tmpearce评论,我使用了一个简单的脚本来衡量运行时间:


To answer @tmpearce comment I used a simple script to measure running time:

a = {[1 2 3]; [4 5]; [6 7 8 9]};
tic
a = cellfun(@(x)[10 x],a,'UniformOutput',0)
toc
a = {[1 2 3]; [4 5]; [6 7 8 9]}; 
tic
for ii=1:numel(a)
    a{ii} = [10 a{ii}];
end
toc

结果:

Elapsed time is 0.002622 seconds.
Elapsed time is 0.000034 seconds.

这篇关于如何在Matlab的单元格数组的每个单元格中插入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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