Preallocation Problem in for loop

3 次查看(过去 30 天)
I have a function which takes a cell array "c" and checks for the length of x and a part of the code is:
str = [];
for i=1:size(c,1)
str = [str;extractBetween( func2str(c{i,1}),'x(',')')];
end
I get the warning that str is not preallocated.
%Examples, how str looks like
c = cell(1,1);
c{1} = @(x) 10*x(1)-x(2)^2
%here str would be a 5 x 1 cell array :
{'1'}
{'2'}
%or:
c = cell(2,1);
c{1} = @(x) 10*x(1)-x(1)^2
c{2} = @(x) x(1)^2+4*x(2);
%here str would be a 4 x 1 cell array :
{'1'}
{'2'}
{'1'}
{'2'}
Would it be possible to preallocate str?

采纳的回答

Voss
Voss 2022-4-6
编辑:Voss 2022-4-6
If you know that every element of c has the same number of instances of 'x(...)', i.e., you know extractBetween returns the same size output for each element of c, then it's easy to pre-allocate str:
c = cell(2,1);
c{1} = @(x) 10*x(1)-x(1)^2;
c{2} = @(x) x(1)^2+4*x(2);
num_x = 2; % two x(...) matches in each element of c
str = cell(num_x*numel(c),1); % pre-allocate
for i=1:size(c,1)
str(num_x*(i-1)+(1:num_x)) = extractBetween( func2str(c{i,1}),'x(',')');
end
disp(str);
{'1'} {'1'} {'1'} {'2'}
However, it may be better to do it in a way that handles differing numbers of matches in each element of c and doesn't require pre-allocation because there's no loop:
% make a new element of c with 3 x's:
c{end+1} = @(x) x(1)^2+4*x(2)+10*x(3);
% use cellfun instead of a loop:
str = cellfun(@(x)extractBetween(func2str(x),'x(',')'),c,'UniformOutput',false);
str = vertcat(str{:})
str = 7×1 cell array
{'1'} {'1'} {'1'} {'2'} {'1'} {'2'} {'3'}

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by