矩阵“之字形"重新排序 [英] Matrix "Zigzag" Reordering

查看:116
本文介绍了矩阵“之字形"重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB中有一个NxM矩阵,我想以与JPEG重新排序其子块像素的方式类似的方式重新排序:

I have an NxM matrix in MATLAB that I would like to reorder in similar fashion to the way JPEG reorders its subblock pixels:

(来自维基百科的图片)

我希望算法是通用的,这样我就可以传递任何尺寸的2D矩阵.我是一名C ++程序员,非常想写一个老式的循环来完成此任务,但是我怀疑在MATLAB中有更好的方法来实现它.

I would like the algorithm to be generic such that I can pass in a 2D matrix with any dimensions. I am a C++ programmer by trade and am very tempted to write an old school loop to accomplish this, but I suspect there is a better way to do it in MATLAB.

我宁愿要一种在NxN矩阵上工作并从那里开始的算法.

I'd be rather want an algorithm that worked on an NxN matrix and go from there.

1 2 3
4 5 6  -->  1 2 4 7 5 3 6 8 9
7 8 9

推荐答案

考虑代码:

M = randi(100, [3 4]);                      %# input matrix

ind = reshape(1:numel(M), size(M));         %# indices of elements
ind = fliplr( spdiags( fliplr(ind) ) );     %# get the anti-diagonals
ind(:,1:2:end) = flipud( ind(:,1:2:end) );  %# reverse order of odd columns
ind(ind==0) = [];                           %# keep non-zero indices

M(ind)                                      %# get elements in zigzag order

具有4x4矩阵的示例:

An example with a 4x4 matrix:

» M
M =
    17    35    26    96
    12    59    51    55
    50    23    70    14
    96    76    90    15

» M(ind)
ans =
    17  35  12  50  59  26  96  51  23  96  76  70  55  14  90  15

以及具有非平方矩阵的示例:

and an example with a non-square matrix:

M =
    69     9    16   100
    75    23    83     8
    46    92    54    45
ans =
    69     9    75    46    23    16   100    83    92    54     8    45

这篇关于矩阵“之字形"重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆