Cell array in a loop

3 次查看(过去 30 天)
gsourop
gsourop 2016-11-9
评论: Mostafa 2016-11-13
Hi everyone,
I have created a cell array of dimensions 1x10, named A. Each element contains a 100x5 matrix. Hence, I got 10 matrices 100x5. However, I want to put every matrix of the cell array into a loop. If Bis a 100x5 matrix, the loop should look like:
for t=1:100;
j=1:5;
x=B(t,j)-A(t,j)
end;
end;
At the end x should deliver a 1x10 cell array that will contain 10 elements of matrices 100x5.
I would appreciate any help. Thank you in advance!

回答(1 个)

Mostafa
Mostafa 2016-11-9
编辑:Mostafa 2016-11-9
% B is already defined, a matrix of doubles
% A is already defined, a cell array of matrices
% B and the matrices in A have the same size
x = cellfun(@(X) B - X, A, 'UniformOutput', 0);
  6 个评论
Guillaume
Guillaume 2016-11-10
While preallocation is indeed advisable, my main reason for creating x beforehand was actually to demonstrate that cellfun creates an output the same shape as the input. Without that preallocation, the output is a row vector.
The problem with length is that you open yourself to bugs if in the future the input changes from vector to multidimensional. The above is a perfect example: if the input is a matrix instead of a vector, your loop will only process the first X elements of the ND cell array, where X is the size of the largest dimension.
My version with numel works with any shape and any number of dimensions.
For that reason, I never use length. If I want to operate over all the elements of the inputs (regardless of shape), I use numel. If I want to operate over a particular dimension, I use size with the dimension specified.
Mostafa
Mostafa 2016-11-13
I'm not arguing with your point, I'm saying that it's a personal preference in case of 1-D arrays (which was the case in the fore mentioned example). In my codes, whenever I see length, I immediately understand that I'm dealing with an array - not a matrix or an input of unspecified size.
I totally agree that the general form is to use numel, or even better: cellfun

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Linear Algebra 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by