How to set up a forloop for calculations between different cells in a cell array?

1 次查看(过去 30 天)
I'm trying to make a forloop where the first looped variable j stays the same for all 1 through 10 iterations of i before it moves on to the next number (2) and then does all 1:10 iterations of i again and so on until the squared difference has been taken from all combinations of cells within cell1. This is what I've been trying but I'm getting a lot of empty cells [] and incorrect values. What is a better way to implement this?
B = repmat(1:10,1,10);
J = repelem([1 2 3 4 5 6 7 8 9 10], 10);
cell1=cell1={2,1,10,4,1,5,12,2,1,4}
for i = B
for j = J
test{i*j} = (cell1{j} - cell1{i}).^2;
end
end

回答(1 个)

Stephen23
Stephen23 2016-3-10
编辑:Stephen23 2016-3-10
"What is a better way to implement this?" You don't tell us what "this" is. If you are trying to calculate the squared difference of two vectors, then your method is very complicated, slow, and buggy. You could simply use bsxfun:
>> V = [2,1,10,4,1,5,12,2,1,4];
>> bsxfun(@(x,y)(x-y).^2, V, V(:))
ans =
0 1 64 4 1 9 100 0 1 4
1 0 81 9 0 16 121 1 0 9
64 81 0 36 81 25 4 64 81 36
4 9 36 0 9 1 64 4 9 0
1 0 81 9 0 16 121 1 0 9
9 16 25 1 16 0 49 9 16 1
100 121 4 64 121 49 0 100 121 64
0 1 64 4 1 9 100 0 1 4
1 0 81 9 0 16 121 1 0 9
4 9 36 0 9 1 64 4 9 0
This gives the square of the difference of every pair of elements in the vector V.
If you are trying to do something else then please explain what you want to do, and then we can help you to reach your goal.
  4 个评论
Stephen23
Stephen23 2016-3-18
It is simpler to process data stored in simple numeric arrays, so the first thing we willl do is to convert that cell array of vectors into one simple numeric array:
C = num2cell(rand(129,30),1); % fake data
% convert to numeric array:
M = cell2mat(C);
% calculate square of differences of the columns:
D = bsxfun(@(x,y)(x-y).^2, M, permute(M,[1,3,2]));
You see, no loops are required.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by