I'd like to replace a specific number of elements of my cell to zero without using for. For example to replace elements of row 2 in example cell a below: How should I proceed possibly using cellfun?
a=cell(2,3);
cellfun(@(x)(zeros(a{x}(2,:))),a);
It gives the error "Bad cell reference operation". what if I'd like to make row 2 empty again? Thanks in advance for any help
The action you want to perform requires an assignment within a function. The only way to achieve this is using eval
, which is considered bad practice.
A loop is therefore the best remaining option, if you want to keep everything in one script:
A = {randn(2,3),randn(2,3)};
for ii = 1:numel(A)
A{ii}(2,:) = 0;
end
If you don't bother using multiple files, you can put the assignment in a function:
function [ out ] = setZero( cellarray, rowidx )
out = cellarray;
out(rowidx,:) = 0;
end
and use it as follows:
A = cellfun(@(x) setZero(x,2),A ,'uni',0)