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

1 回表示 (過去 30 日間)
mzaya
mzaya 2016 年 3 月 10 日
コメント済み: Stephen23 2016 年 3 月 18 日
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 件のコメント
mzaya
mzaya 2016 年 3 月 14 日
Yes, my cell array has 1X30 cells and each cell is of equal size of 129X1.
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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by