How to insert a number to every cell of a cell array in Matlab?

ぐ巨炮叔叔 提交于 2019-12-06 14:16:04

问题


I have a cell array like this:

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

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

Is it possible to do it without any for loop?


回答1:


You can use CELLFUN with anonymous function:

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

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

The results:

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


来源:https://stackoverflow.com/questions/15181294/how-to-insert-a-number-to-every-cell-of-a-cell-array-in-matlab

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