How to carry index within a function?

2 次查看(过去 30 天)
Hi all,
This is a very long question ;-)
I have a function which sort a grid to cell blocks, the function is:
function [otpt] = GridtoBlock(inpt)
xy = cellfun(@unique, num2cell(inpt, 1), 'UniformOutput', false);
x = xy{1};
y = xy{2};
otpt = cell(numel(y) - 1, numel(x) - 1);
for xidx = 1 : numel(x) - 1
for yidx = 1 : numel(y) - 1
otpt{yidx, xidx} = [repmat(x(xidx:xidx+1), 2, 1), repelem(y(yidx:yidx+1), 2)];
end
end
for i_rte = 1:numel(otpt)
otpt_temp = otpt{i_rte};
otpt{i_rte}(3, :) = otpt_temp(4, :);
otpt{i_rte}(4, :) = otpt_temp(3, :);
end
If the inpt is (a square domain contains 3 by 3 points):
inpt_noindex = [-1 -1; -1 1; 1 -1; 1 1; -1 0; 0 -1; 0 0; 0 1; 1 0];
then the otpt is:
otpt_noindex =
[4x2 double] [4x2 double]
[4x2 double] [4x2 double]
otpt_noindex{:}
ans =
-1 -1
0 -1
0 0
-1 0
ans =
-1 0
0 0
0 1
-1 1
ans =
0 -1
1 -1
1 0
0 0
ans =
0 0
1 0
1 1
0 1
i.e. the function automatically sort the x and y coordinates and put them into a 2 by 2 cell block.
Now my question is, if I find the row index of inpt, i.e.
inpt_index = [1 -1 -1; 2 -1 1; 3 1 -1; 4 1 1; 5 -1 0; 6 0 -1; 7 0 0; 8 0 1; 9 1 0];
How can I modify the function to get the otpt with the original row index? i.e. I want the otpt to be
otpt_index =
[4x3 double]
[4x3 double]
[4x3 double]
[4x3 double]
otpt_index{:}
ans =
1 -1 -1
6 0 -1
7 0 0
5 -1 0
ans =
5 -1 0
7 0 0
8 0 1
2 -1 1
ans =
6 0 -1
3 1 -1
9 1 0
7 0 0
ans =
7 0 0
9 1 0
4 1 1
8 0 1
The goal is to make the row index follows the matrix operation. I have written a for loop using isequal to compare each block against the inpt, but this is not efficient when the inpt becomes large.
Thanks a lot!
  2 个评论
KSSV
KSSV 2016-11-16
for
inpt = [1 -1 -1; 2 -1 1; 3 1 -1; 4 1 1; 5 -1 0; 6 0 -1; 7 0 0; 8 0 1; 9 1 0];
your otpt is of size 2X8 with element as 4x2 double. This you want to change to what size?
Xiaohan Du
Xiaohan Du 2016-11-16
Hi KSSV,
For
inpt_index = [1 -1 -1; 2 -1 1; 3 1 -1; 4 1 1; 5 -1 0; 6 0 -1; 7 0 0; 8 0 1; 9 1 0];
I'd like to have the same sort method, but only 'carry' the original index with the sorted blocks.
If you compare the otpt_index against otpt_noindex, you'll find that otpt_index is the 2nd and 3rd column of otpt_noindex, the only difference between otpt_index and otpt_noindex is the 1st column of otpt_index, which is the original row index from inpt_index.
I hope this is clear.

请先登录,再进行评论。

回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by