基本上你是想獲得一個矩陣,當與new_x
和new_y
索引會給我們vals
,即 -
output(new_x(1,1),new_y(1,1))
必須等於vals(1,1)
,
output(new_x(1,2),new_y(1,2))
必須等於vals(1,2)
等。
我們將盡力在稍後進行驗證。現在,這裏是一個使用linear indexing
一個解決方案 -
nrows = size(vals,1); %// Store number of rows
%// Calculate linear indices
idx = (new_x + (new_y-1)*nrows);
%// Trace/map back to sorted version of "1:numel(vals)"
[~,traced_back_idx] = sort(idx(:));
%// Index into vals with traced back linear indices & then reshape & transpose
out = reshape(vals(traced_back_idx),[],nrows).'
下面是另一個,可能更快捷的方式 -
out = nan(size(vals));
out((new_x + (new_y-1)*nrows)) = vals;
out = out.'
正如前面覈查討論,讓我們索引out
與new_x
和new_y
和應匹配了vals
。這裏有一個代碼,這樣做 -
for ii = 1:size(out,1)
for jj = 1:size(out,2)
check_back(ii,jj) = out(new_y(ii,jj),new_x(ii,jj));
end
end
樣品試驗 -
案例#1(樣品被從提問):
vals =
1 2
3 4
new_x =
1 2
2 1
new_y =
2 2
1 1
new_vals =
4 3
1 2
out =
4 3
1 2
check_back = (must be same as vals)
1 2
3 4
案例#2:
vals =
1 2 5
3 4 5
6 8 3
new_x =
1 2 3
3 1 2
3 2 1
new_y =
2 2 3
2 1 1
1 3 3
out =
4 5 6
1 2 3
3 8 5
check_back = (must be same as vals)
1 2 5
3 4 5
6 8 3
從你的描述我不明白輸出'new_vals',你能解釋它一步一步或添加for循環實現? – Daniel
@Daniel我認爲從'new_x'和'new_y'計算出的線性指數要追溯到從'1到numel(vals)'的線性指數。這有點像映射回來,如果我說得對。 – Divakar
@Daniel ..或追溯到'1到numel(vals)'的排序版本。 – Divakar