Finding and setting new values for matrix elements within a cell array
6 次查看(过去 30 天)
显示 更早的评论
I have several large cell arrays (e.g., 9x9 cell) where each cell is composed of a large matrix (e.g., 800x200 double). I'd like to find all of a certain type of element within each matrix in each cell and set it equal to a new value. I'm asking this in a general form because I've run into this problem on many occasions now, but just for example, all elements equal to 0 or NaN.
I can do this easily for data in a matrix:
x = [0:10,NaN];
x(x==0) = 1;
x(isnan(x)) = 11;
but I haven't been able to find an elegant way to do the same thing when the data is in cells. This is as far as I've gotten:
a = {[0:5] [5:10,NaN];[10:20] [zeros(5,8)]};
ind = cellfun(@(elem)elem==0,a,'uniform',0); %generates a logical array indexing the elements I want in each cell
cellfun(@(a,ind)a(ind),a,ind,'uniform',0); %returns cell array containing only the values I want to reference from each cell
but I'm trying for something like the following, which won't work:
cellfun(@(a,ind)a(ind)=1,a,ind,'uniform',0); %set ind elements of all cells in a equal to 1
I do realize I can accomplish what I'm trying to do with for loops:
for i = 1:size(a,1)
for j = 1:size(a,2)
a{i,j}(a{i,j}==0) = 1;
end
end
but this is more of a question about whether it's even possible to do what I want to do (there are also several cases in my data where a for loop like this would be clunky and I would legitimately really like to be able to do this in just one line). Any help would be much appreciated, thanks!
0 个评论
回答(1 个)
Stephen23
2018-9-28
编辑:Stephen23
2018-9-28
The simplest and most efficient solution is to use a for loop.
But then you write "...there are also several cases in my data where a for loop like this would be clunky and I would legitimately really like to be able to do this in just one line". Okay, then lets do this in one line by defining a function:
function x = myfun(x)
x(x==0) = 1;
x(isnan(x)) = 11;
end
and then calling it using cellfun:
C = cellfun(@myfun,C,'uni',0)
You could easily parametrize the function to match/replace different values:
Using a nested function is another option, which might be an advantage if the arrays are large.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!