Redefining values within cell array using cellfun

6 views (last 30 days)
Suppose I have a cell array of matrices, and I want to define certain elements of the arrays of each cell as a value, and then return those values to the corresponding elements of that matrix.
Would it be possible to do this using cellfun to operate on each cell? The below example highlights what I'm aiming for.
I have cell array C of arrays. I want to replace the elements 1:x:end of the array in each cell in C with 1. However, doing this element-by-element would be impractical, as would looping. I want all other elements to remain the same.
  1 Comment
Evan
Evan on 3 Feb 2012
Just to note, I'm running into this problem due to the fact that cellfun doesn't support explicit assignments.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Feb 2012
function x = assignat(x, L, v)
x[L] = v;
end
newC = cellfun( @(T) assignat(T, 1:x:length(T), 1), C );
Note, though, that this is really just hiding a "for" loop, and that it would be expected that other forms would be faster, such as
newC = C;
for K = 1 : numel(C)
newC{K}(1:x:end) = 1;
end
I think it might be possible to code the cellfun() without using the auxiliary user function "assignat" that I invented, but the expressions would get complicated and would involve calls to several MATLAB functions -- no time saved.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!