How to reshape two cell arrays of strings into a cell array of cell arrays

2 ビュー (過去 30 日間)
Paolo Binetti
Paolo Binetti 2017 年 3 月 4 日
コメント済み: Star Strider 2017 年 3 月 4 日
Is there a neat way to vectorize the for-loop below?
n_nodes = 2^(20-1);
nodes = cellstr(dec2bin(0:n_nodes-1))';
suffixes = [nodes nodes];
row1 = suffixes(:,1:2:end);
row2 = suffixes(:,2:2:end);
edges = cell(1,n_nodes);
for i = 1:n_nodes
edges(i) = {[row1(i) row2(i)]};
end

採用された回答

Star Strider
Star Strider 2017 年 3 月 4 日
I did not time this with respect to your loop, so I don’t know if it’s faster:
edges = mat2cell([row1' row2'], ones(1,size(row1,2)), 2);
This creates a column vector of cells. Transpose it if you want a row vector of cells:
edges = mat2cell([row1' row2'], ones(1,size(row1,2)), 2)';
  2 件のコメント
Paolo Binetti
Paolo Binetti 2017 年 3 月 4 日
I timed it and it's 15x faster. Thank you.
Star Strider
Star Strider 2017 年 3 月 4 日
My pleasure!

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

その他の回答 (1 件)

John BG
John BG 2017 年 3 月 4 日
Hi Paolo
the following has the same size and type as the result of your for loop
A=reshape({row1{:} row2{:}},2,8);B=A'
B
=
'000' '010'
'100' '110'
'000' '010'
'100' '110'
'001' '011'
'101' '111'
'001' '011'
'101' '111'
whos('B')
Name Size Bytes Class Attributes
B 8x2 1888 cell
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG
  1 件のコメント
Paolo Binetti
Paolo Binetti 2017 年 3 月 4 日
Hi John, thank you but I am not getting the same result.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by