Increase size of array within cellfun
Show older comments
I have a cell array with each cell containing a 4x4 double array. I want to add an additional value at position (5,5), and thus increase the size of each double array to 5x5. The double arrays will not always be 4x4, but whatever nxm is, I just need to append one additional element in the (n+1)x(m+1) position
I'd rather avoid looping over each cell, can this be done with cellfun? My code below uses '=' within cellfun which is not supported.
n = 4;
m = 4;
A = rand(n,m); B = rand(n,m); C = rand(n,m); D = rand(n,m);
ABCD = {A,B;C,D}; % 2x2 cell array
% ABCD = cellfun(@(x) x(end+1,end+1) = 0, ABCD) % code that doesn't work
Thanks!
Accepted Answer
More Answers (1)
Dyuman Joshi
on 19 Sep 2023
Edited: Dyuman Joshi
on 19 Sep 2023
"I'd rather avoid looping over each cell, can this be done with cellfun?"
That's the thing - Cellfun is just a loop in disguise.
Looping is the way to go here.
%Bigger Cell array for testing
n = 800;
m = 1000;
A = rand(n,m); B = rand(n,m); C = rand(n,m); D = rand(n,m);
ABCD = {A,B;C,D;A,B;C,D;A,B;C,D;A,B;C,D;A,B;C,D;A,B;C,D;A,B;C,D;A,B;C,D};
%value to append
val = 2;
F1 = @() CELL(ABCD,n,m,val);
F2 = @() LOOP(ABCD,n,m,val);
isequal(F1(),F2())
fprintf('Time taken by cellfun = %f seconds', timeit(F1))
fprintf('Time taken by loop = %f seconds', timeit(F2))
%% If you want to use cellfun, this is one way to do it
function z = CELL(z,n,m,val)
z = cellfun(@(x) [x zeros(n,1);zeros(1,m) val], z, 'uni', 0);
end
%% Loop method
function z = LOOP(z,n,m,val)
for k=1:numel(z)
z{k}(n+1,m+1) = val;
end
end
1 Comment
Let's compare the speed of all approaches in this thread -
%Bigger Cell array for testing
n = 800;
m = 1000;
A = rand(n,m); B = rand(n,m); C = rand(n,m); D = rand(n,m);
ABCD = {A,B,C,D;A,B,C,D;A,B,C,D;A,B,C,D;A,B,C,D;A,B,C,D};
%value to append
val = 2;
F1 = @() CELL(ABCD,n,m,val);
F2 = @() LOOP(ABCD,n,m,val);
F3 = @() SUBTITUTE(ABCD,n,m,val);
F4 = @() HELPER(ABCD,val);
%% Check if outputs are equal or not
isequal(F1(),F2(),F3(),F4())
fprintf('Time taken by cellfun = %f seconds', timeit(F1))
fprintf('Time taken by loop = %f seconds', timeit(F2))
fprintf('Time taken by substitute = %f seconds', timeit(F3))
fprintf('Time taken by helper = %f seconds', timeit(F4))
function z = CELL(z,n,m,val)
z = cellfun(@(x) [x zeros(n,1);zeros(1,m) val], z, 'uni', 0);
end
function z = LOOP(z,n,m,val)
for k=1:numel(z)
z{k}(n+1,m+1) = val;
end
end
function z = SUBTITUTE(z,n,m,val)
z = cellfun(@(x) subsasgn(x,substruct('()',{n+1,m+1}),val), z, 'UniformOutput',false);
end
function z = HELPER(z,val)
z = cellfun(@(x) extend_matrix_by_one(x,val), z, 'UniformOutput',false);
% helper function definition
function x = extend_matrix_by_one(x,val)
x(end+1,end+1) = val;
end
end
Categories
Find more on Image Arithmetic in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!