Assigning row to array using cellfun

5 ビュー (過去 30 日間)
Konrad Warner
Konrad Warner 2019 年 11 月 11 日
コメント済み: Konrad Warner 2019 年 11 月 12 日
Hello,
I have a 1x4 cell array, each cell contains a 1000x8 zeros array:
A = arrayfun(@(~) zeros(1000,8),(1:4),'un',0);
Now I want to assign every same row (definded by a background counter) with a new array same length, e.g B = [1 1 1 1 1 1 1 1]
The following loop discribes it quite well...
counter = randi(1000) % any row
for i = 1:4
A{i}(counter,:) = B;
end
I was just wondering if there is a way doing it with cellfun?
  1 件のコメント
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 11 月 11 日
maybe this code can help you
A=zeros(1000,1);
counter = randi(1000); % any row
A(counter)=1;
A=repmat({repmat(A,1,8)},1,4)

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

採用された回答

Adam Danz
Adam Danz 2019 年 11 月 11 日
編集済み: Adam Danz 2019 年 11 月 11 日
Here's your loop, within cellfun().
A = cellfun(@(x)[x(1:counter-1,:);B;x(counter+1:end,:)], A, 'UniformOutput', false);
  3 件のコメント
Adam Danz
Adam Danz 2019 年 11 月 11 日
Really? I just timed the loop method from your question and the cellfun() method from my answer. Each method was repeated 100,000 times and each iteration was timed using tic/toc. When comparing the median speeds, the loop method was ~22 times faster than the cellfun method (I repeated that process twice and got nearly the same results).
The cellfun() method is (arguably) cleaner and reduces the number of lines of code but often times loops are faster than cellfun(), arrayfun() etc. I wonder if your timing test involved additional computations.
Konrad Warner
Konrad Warner 2019 年 11 月 12 日
Sorry you are right. I didn't repeat the methodes (which doesn't make sense, comparing such short elapsed times). The Loop is much faster, good to know, wouldn't have check twice.

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by