フィルターのクリア

indices of a spiral

5 ビュー (過去 30 日間)
Boris Povazay
Boris Povazay 2018 年 4 月 20 日
編集済み: Stephen23 2018 年 4 月 20 日
It is simple to geerate a growing spiral matrix vial the spiral function:
S=spiral(3)
which yields a nice spiral matrix:
S =
7 8 9
6 1 2
5 4 3
However it is not straight forward to generate the list of indices for that sequence:
[2,2], [3,2], [3,3], [2,3], [1,3], ...
Does anyone have an idea for a one-liner that can do this?
  1 件のコメント
Stephen23
Stephen23 2018 年 4 月 20 日

You have swapped the dimensions: from smallest to largest the indices are actually

(2,2) (2,3) (3,3) (3,2) (3,1) (2,1) (1,1) (1,2) (1,3)

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 4 月 20 日
編集済み: Stephen23 2018 年 4 月 20 日

Not quite one line, but you can use sort and ind2sub for this:

>> M = spiral(3)
M =
   7   8   9
   6   1   2
   5   4   3
>> [~,idx] = sort(M(:));
>> [R,C] = ind2sub([3,3],idx);
>> [R,C]
ans =
   2   2
   2   3
   3   3
   3   2
   3   1
   2   1
   1   1
   1   2
   1   3

Or copy the spiral Mfile to your user directory, give it a new name, and edit it to return the indices. It wouldn't be hard to do this, just remember to preallocate the output matrices! Note that the file is copyright.

  2 件のコメント
Boris Povazay
Boris Povazay 2018 年 4 月 20 日
Thanks for the quick reply and the solution. That ind2sub in combination with the sorting indices does the trick - I got stuck after assigning the indices form the sort function. As you say the spiral(n) function is copyrighted, which makes me wonder if this is maintained code and where one might ask for an implementation that also generates the indices directly. Best regards!
Stephen23
Stephen23 2018 年 4 月 20 日
編集済み: Stephen23 2018 年 4 月 20 日

@Boris Povazay: that specific code is copyright... but I doubt that the algorithm is: online you can find plenty of implementations of the Ulam spiral, e.g.:

https://rosettacode.org/wiki/Ulam_spiral_(for_primes)

which relies on exactly that arrangement of numbers. Note that the Ulam spiral is flipped vertically relative to the MATLAB spiral (in other words: MATLAB is clockwise, Ulam spiral is counter-clockwise). I am sure you could easily implement a version which generates the indices directly.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by