i have a 1D cell array . i wish to increase its size by adding zeros to its right . i think i can use pad array with LOC as 'b' but i dont know the synax. help me with this please.

 採用された回答

Image Analyst
Image Analyst 2015 年 4 月 27 日

0 投票

Try this:
ca{1} = 'abc' % Put string in first cell.
% Now pad with cells that have a numerical zero in them.
for k = 2 : 15
ca{k} = 0;
end

4 件のコメント

Nabhdeep Bansal
Nabhdeep Bansal 2015 年 4 月 30 日
thank you sir
Stephen23
Stephen23 2015 年 4 月 30 日
No preallocation and a slow loop, this is a poor solution as the cell array gets expanded and MATLAB has to keep reallocating memory... see my answer for a faster and neater solution.
Image Analyst
Image Analyst 2015 年 4 月 30 日
Yes, your way is faster and more "MATLAB-ish" which is why I voted for it. Though for only 15 cells you won't notice. My method took only 40 microseconds:
Elapsed time is 0.000040 seconds.
With a million elements to set it gets almost up to a second while your method stays short (around 15 microseconds).
Stephen23
Stephen23 2015 年 4 月 30 日
編集済み: Stephen23 2015 年 4 月 30 日
Of course for small arrays it will not make much difference... but surely it is just as easy to learn good habits rather than to have to unlearn bad ones?
After all today's undergrad is tomorrows PhD candidate, and then it really will make a difference to their muon-path dataset analysis.
Thank you for the vote!

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

その他の回答 (2 件)

Stephen23
Stephen23 2015 年 4 月 27 日
編集済み: Stephen23 2015 年 4 月 27 日

5 投票

A fast and neat way to do this would be to use basic MATLAB indexing and scalar expansion:
>> ca{1} = 'abc'
>> ca(2:15) = {0}; % put whatever value you want in this scalar cell
Just one line of code and no loops are required to extend a cell array. Note that that curly brackets and parentheses are deliberate!
Thorsten
Thorsten 2015 年 4 月 27 日

0 投票

Sample cell
C{1} = 100;
C{2} = rand(2);
C{3} = 'a';
% add zeros up to cell 23
C{23} = 0;
z0{1} = 0;
C(logical(cellfun(@isempty, C))) = deal(z0);

1 件のコメント

Thorsten
Thorsten 2015 年 4 月 27 日
See Stephen's answer for the easy and better way to do it...

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

カテゴリ

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

製品

質問済み:

2015 年 4 月 27 日

編集済み:

2015 年 4 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by