matlab - 在matlab中转置二维矩阵的线性索引
问题描述
我想有效地转置我的二维矩阵的线性索引,并且我努力想出有效的代码来做到这一点(见下文我的次优解决方案)。如何尽可能高效地完成这项工作(RAM 无关紧要,只是速度)?
假设我们有一个二维矩阵a
:
a = [1:4;5:8;9:12;13:16;17:20]'
a =
1 5 9 13 17
2 6 10 ->14<- 18
3 >7< 11 15 19
4 8 12 16 20
现在我有一些索引,比如7
and 14
,我真的很想转置,这样7
(3,2) 的索引变为12
(2,3) 并且14
(4,2) 变为9
(2,4)。
>> a'
ans =
1 6 11 16
2 7 >12< 17
3 8 13 18
4 ->9<- 14 19
5 10 15 20
现在,我用了一些愚蠢的东西:
tmp = zeros(size(a));
tmp([7 14])=1; %mark linear indices as '1' in the matrix
tmp=tmp'; %transpose the whole matrix
solution = find(tmp);
%then some sorting...
solution =
9
12
(显然,ind2sub
可以简单地获取索引,然后翻转它们。我正在寻找一种更有效的解决方案,我可以直接转换索引,而不需要额外的变量)
解决方案
如果我正确理解你的问题,这就是你想要的:
sz = [4 5]; % size of original a
input_ind = [7 14]; % input linear indices
row_ind = mod(input_ind-1,sz(1))+1; % row indices from input linear indices
col_ind = floor((input_ind-1)/sz(1))+1; % column indices from input linear indices
output_ind = col_ind + (row_ind-1)*sz(2); % output linear indices, obtained using
% col_ind as row indices, row_ind as column indices, and sz(2) instead of sz(1)
推荐阅读
- c - 当应用于链表中的指针时,AND 运算符是什么意思?
- c# - 如何使用@Html.ActionLink 显示带参数的索引视图?
- javascript - 用服务器端渲染反应路由器模式路由
- javascript - 奇怪的javascript循环行为
- android-fragments - 在片段中使用 RecyclerView 时询问权限时应用程序崩溃
- facebook - 如何通过facebook api获取其他人对我的帖子的评论
- image - 使用 imagesc 函数查看矩阵的不同平面
- javascript - Javascript 无法提醒字典
- javascript - 如何使用 javascript 微软认证?
- java - Spring 不显示 home.html