Cellfun:如何对矩阵的单元格阵列中的每一行求和? Matlab的 [英] Cellfun : How to sum each row in a cell array of matrices? Matlab
问题描述
假设我有3x3的单元格,每个单元格包含9x9的矩阵,我将如何使用cellfun求和整个单元格阵列的每一行?
Say I have 3x3 cells, each cell containing a matrix of 9x9, how would I go about using cellfun to sum each row of the entire cell array?
当尝试在大括号中使用:时,我不断收到错误坏单元格引用".
I keep obtaining the error ''bad cell reference'' when I try to use the : in the curly brackets.
我宁愿不将其转换为矩阵,然后再次返回单元格.
I'd rather not convert it to a matrix then back to cells again.
非常感谢您的智慧!
推荐答案
这里是将每个矩阵的行与一个单元格相加的解决方案,如果您仔细阅读cellfun
的文档,我认为您应该可以它.
Here is the solution for summing row of each matrix with a cell , if you read the documentation of cellfun
carefully, I think you should be able to get it.
clc;
clear all;
a=cell(3,3);
for i=1:3
for j=1:3
a{i,j}=randi(10,[9 9]);
end
end
row_sum_cell=cellfun(@(a) sum(a,2),a,'UniformOutput',false);
以下解决方案对单元格数组中的整个行求和:
The following solution sums the entire row across the cell array:
clc;
clear all;
a=cell(3,3);
for i=1:3
for j=1:3
a{i,j}=randi(10,[9 9]); %generating the cell array
end
end
[r,c]=size(a); %getting the size of the array to concatenate it at runtime
horzCat_A=cell(r,1);
for i=1:r
for j=1:c
horzCat_A{i,1}=[horzCat_A{i,1} a{i,j}]; %concatenating
end
end
%after getting a concatenated matrix, apply a cellfun same as in previous example.
cell_row_sum=cellfun(@(horzCat_A) sum(horzCat_A,2),horzCat_A,'UniformOutput',false);
这篇关于Cellfun:如何对矩阵的单元格阵列中的每一行求和? Matlab的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!