How to transpose cell arrays within a larger cell array
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi, I was wondering how to use cellfunc to find and transpose cell arrays that are row orientated within another cell array. I can do it using a loop but I was curious how to use cell function.
Code is below, I think there is a flaw in the method because I am using a loop mentality using seperate variables.
The dynamics file is a {1x3} cell and embedded within this are another set of {3x1} cells with uniform matrices. The third cell is the one that is row and ebThe 3rd cell is the one I can change, but I still think that on a larger scale my method will cause probelms.
If someone could have a quick it would be appreciated.
Thanks
load('dynamics.mat')
%find rows in cell array
idx = find(cellfun(@isrow, dyn));
trans_dyn = (cellfun(@transpose, dyn(idx), 'UniformOutput', false));
dyn(idx) = trans_dyn;
댓글 수: 0
채택된 답변
Jan
2021년 3월 31일
편집: Jan
2021년 3월 31일
"The dynamics file is a {1x3} cell and embedded within this are another set of {3x1} cells with uniform matrices." - What are "uniform matrices?
"I still think that on a larger scale my method will cause probelms." - Why do you assume this?
idx = cellfun(@isrow, dyn); % Omit the FIND for faster logical indexing
dyn(idx) = cellfun(@transpose, dyn(idx), 'UniformOutput', false);
Or easier in 1 step:
dyn = cellfun(@(c) c(:), dyn, 'UniformOutput', false)
All these methods are slow.
Data = load('dynamics.mat');
dyn0 = repmat(Data.dyn, 1, 1e5); % A larger set
dyn = dyn0;
tic;
idx = find(cellfun(@isrow, dyn));
trans_dyn = (cellfun(@transpose, dyn(idx), 'UniformOutput', false));
dyn(idx) = trans_dyn;
toc % Elapsed time is 1.827274 seconds.
dyn = dyn0;
tic;
idx = cellfun(@isrow, dyn); % Omit the FIND for faster logical indexing
dyn(idx) = cellfun(@transpose, dyn(idx), 'UniformOutput', false);
toc % Elapsed time is 1.794807 seconds.
dyn = dyn0;
tic;
dyn = cellfun(@(c) c(:), dyn, 'UniformOutput', false);
toc % Elapsed time is 3.947908 seconds.
dyn = dyn0;
tic;
dyn = cellfun(@(c) reshape(c, [], 1), dyn, 'UniformOutput', false);
toc % Elapsed time is 2.599826 seconds.
dyn = dyn0;
tic;
for k = 1:numel(dyn)
dyn{k} = dyn{k}(:);
end
toc % Elapsed time is 1.523816 seconds.
dyn = dyn0;
tic;
for k = 1:numel(dyn)
dyn{k} = reshape(dyn{k}, [], 1);
end
toc % Elapsed time is 0.515385 seconds.
dyn = dyn0;
tic;
for k = 1:numel(dyn)
if isrow(dyn{k})
dyn{k} = dyn{k}(:);
end
end
toc % Elapsed time is 0.744554 seconds.
dyn = dyn0;
tic;
for k = 1:numel(dyn)
if isrow(dyn{k})
dyn{k} = reshape(dyn{k}, [], 1);
end
end
toc % Elapsed time is 0.433867 seconds.
dyn = dyn0;
tic;
for k = 1:numel(dyn)
if isrow(dyn{k})
dyn{k} = dyn{k}.';
end
end
toc % Elapsed time is 0.392983 seconds.
Prefer loops. cellfun is nice, but slower than a loop.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!