Arrays 避免matlab中的循环

Arrays 避免matlab中的循环,arrays,matlab,for-loop,matrix,while-loop,Arrays,Matlab,For Loop,Matrix,While Loop,我在matlab中对循环的使用有限,我有一个任务。我有矩阵2xn,带有数字和单元格数组1xn。第一行中的每个元素都指向数组的一个位置。我想把矩阵第二行中的每个数字加到单元格中,单元格由第一行中相应的数字表示。另外,我希望单元格是字符串 让我举例说明: A=[[1 4 3 3 1 4 2],[7 4 3 5 6 5 4] 我想获取单元格数组:{76',4',35',45'} 如果不使用for或while循环,我怎么能做到这一点呢?好吧,只要指向、,我就傲慢了。因此,我试图通过在更具建设性的解决方案

我在matlab中对循环的使用有限,我有一个任务。我有矩阵
2xn
,带有数字和单元格数组
1xn
。第一行中的每个元素都指向数组的一个位置。我想把矩阵第二行中的每个数字加到单元格中,单元格由第一行中相应的数字表示。另外,我希望单元格是字符串

让我举例说明:

A=[[1 4 3 3 1 4 2],[7 4 3 5 6 5 4]

我想获取单元格数组:
{76',4',35',45'}


如果不使用
for
while
循环,我怎么能做到这一点呢?

好吧,只要指向、,我就傲慢了。因此,我试图通过在更具建设性的解决方案中实际使用其中的一些方法来弥补:

%// Using array-indexing to find all matches with the current index in the first row, 
%// then print their counterpart(s) into strings
fun = @(ii) sprintf('%d', A(2, A(1, :) == ii));  
%// The following could also be 1:size(A, 2) or unique(A(1, :)) depending on the 
%// general form of your problem.
range = min(A(1, :)) : max(A(1, :));   
%// Using arrayfun to loop over all values in the first row
R = arrayfun(fun, range, 'UniformOutput', false)

好吧,只是指着,,我很傲慢。因此,我试图通过在更具建设性的解决方案中实际使用其中的一些方法来弥补:

%// Using array-indexing to find all matches with the current index in the first row, 
%// then print their counterpart(s) into strings
fun = @(ii) sprintf('%d', A(2, A(1, :) == ii));  
%// The following could also be 1:size(A, 2) or unique(A(1, :)) depending on the 
%// general form of your problem.
range = min(A(1, :)) : max(A(1, :));   
%// Using arrayfun to loop over all values in the first row
R = arrayfun(fun, range, 'UniformOutput', false)
第二行(
unique
)用于删除第一行中可能存在的间隙。否则,这些间隙将转化为accumarray的结果,这将无用地占用更多内存

第三行(
accumarray
)汇总了
A
第二行中第一行中具有相同值的所有值。聚合由匿名函数完成,该函数将数字转换为字符串(
num2str
),删除空格(
regexprep
),并更改方向(
fliplr
)以匹配所需的输出格式

编辑:

由于@chappjc的建议,第三行可以简化为

R = accumarray(ii(:),A(2,:),[],@(v) {fliplr(num2str(v(:).','%d'))}).';
第二行(
unique
)用于删除第一行中可能存在的间隙。否则,这些间隙将转化为accumarray的结果,这将无用地占用更多内存

第三行(
accumarray
)汇总了
A
第二行中第一行中具有相同值的所有值。聚合由匿名函数完成,该函数将数字转换为字符串(
num2str
),删除空格(
regexprep
),并更改方向(
fliplr
)以匹配所需的输出格式

编辑:

由于@chappjc的建议,第三行可以简化为

R = accumarray(ii(:),A(2,:),[],@(v) {fliplr(num2str(v(:).','%d'))}).';

你是怎么想出这么复杂的表达法的:P?@Parag:-)我补充了一些解释,并不是说它有多复杂。。。你可以不用
regexprep
,因为
num2str
有一个格式说明符,它不产生空格:
num2str([7 6],“%d”)
。或者您可以使用
sprintf('%d',[7-6])
我想您只是!:)但是,我同意,它确实打开了许多有趣的门!你是怎么想出这么复杂的表达法的:P?@Parag:-)我补充了一些解释,并不是说它有多复杂。。。你可以不用
regexprep
,因为
num2str
有一个格式说明符,它不产生空格:
num2str([7 6],“%d”)
。或者您可以使用
sprintf('%d',[7-6])
我想您只是!:)但是,我同意,它确实打开了许多有趣的门!