How to fill a cell array without using a loop

Hi,
Assuming that we have an array of integers, for example a = [2 4 3], I am trying to create a cell array where each
cell contains arrays given by [-a(i) : 1 : a(i)] where a(i) is an arbitrary element i in the array a. So the example
a = [2 4 3] would result in a cell array c = {[-2 : 1 : 2], [-4 : 1 4], [-3 : 1 : 3]}.
I know how this can be done with a for loop but I was wondering if there is a way to do it without loops?

 採用された回答

madhan ravi
madhan ravi 2019 年 8 月 7 日
編集済み: madhan ravi 2019 年 8 月 7 日

1 投票

I'm not sure of any other method but here is one with implicit loop:
c = arrayfun(@(x) -x:x, a,'un',0)
celldisp(c)
Or another method with accumarray():
c = accumarray((1:numel(a)).',a,[],@(x){-x:x})
celldisp(c)
Gives:
>> celldisp(c)
c{1} =
-2 -1 0 1 2
c{2} =
-4 -3 -2 -1 0 1 2 3 4
c{3} =
-3 -2 -1 0 1 2 3

1 件のコメント

radius236
radius236 2019 年 8 月 7 日
Thanks a lot, it works.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by