How to write string to all elements of cell array?

10 ビュー (過去 30 日間)
LoroEE
LoroEE 2022 年 4 月 8 日
コメント済み: Image Analyst 2022 年 4 月 8 日
I have an cell array of many rows and 1 column. I want to write the variable in all of those elements.
I can't find the command to write in all elements. I can only write in one of those elements, like so:
name = 'Marley'
size = 8
name_list = cell(size,1)
name_list{size} = name
name_list =
8×1 cell array
{0×0 double} % I want them all to be the 'name' variable
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{'Marley' }
  1 件のコメント
LoroEE
LoroEE 2022 年 4 月 8 日
編集済み: LoroEE 2022 年 4 月 8 日
I can do this with a loop, but there's probably a better way.
for k = 1:size
name_list{k} = name;
end

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

採用された回答

Image Analyst
Image Analyst 2022 年 4 月 8 日
What's wrong with that? It's fast. It's simple. It's intuitive and easy to understand, and thus maintainable by anyone who inherits your code. Looks fine to me.
However, you could do this:
name_list = cell(8, 1);
name_list(:) = {'abcdef'}
name_list = 8×1 cell array
{'abcdef'} {'abcdef'} {'abcdef'} {'abcdef'} {'abcdef'} {'abcdef'} {'abcdef'} {'abcdef'}
Don't use size as the name of your variable since it's the name of a very important built-in function.
  2 件のコメント
LoroEE
LoroEE 2022 年 4 月 8 日
Nothing wrong, I just spend a lot of time looking for this notation.
The specific combination of parenthesis and brackets in each case is very confusing. Is there some documentation about this?
Thanks!
Image Analyst
Image Analyst 2022 年 4 月 8 日
@LoroEE I think reading the FAQ should give you a pretty good intuitive feel for when to use braces, brackets, or parentheses.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by