問題
你有一個二維矩陣。 您使用 Loc 函數來定位感興趣的元素,但 Loc 返回一維矩陣的索引。 如何將一維索引轉換回二維索引?
解決方案
您需要使用 Floor 和 Mod 函數,並且需要知道二維矩陣中的列數。 這是三行,隱藏在下面的註釋示例中。 pixmat 是一個 2D 矩陣,Loc 正在查找非零像素,即黑色:
blacklocs = (Loc( pixmat ) - 1); // blacklocs 是一維索引矩陣(從 0 開始)
rowlocs = Floor( (blacklocs) / nc ) + 1; // nc 是 2D pixmat 中的列數
collocs = Mod( (blacklocs), nc ) + 1; // rowlocs 和 collocs 是 2D 索引(從 1 開始)
// we need a bitmap to work with; use a text box with a moderate size font
textbox = Text Box( "Gargoyle", <<SETFONTSIZE> .5 are antialiasing fading to white background of the "paper".
// the next statement makes the 0 to .5 values be 1 and the .5 to 1 values be 0
pixmat = pixmat < .75; // cut off edge at some gray value. flip the 0..1 significance.
// the pixels are in a 2D matrix of rows and cols. get the dimensions.
nr = N Rows( pixmat );
nc = N Cols( pixmat );
// now we can find the location of the black pixels (1s) that form the text.
// the LOC function returns a 1D matrix of the offsets of non-zero
// elements in the 2D matrix pixmat. if pixmat was 3 rows of 5 elements each,
// the LOC could return a 1D matrix of 0 to 15 elements with values from 1 to 15.
// JMP uses 1-based indexing. subtract one to get 0-based for future steps.
blacklocs = (Loc( pixmat ) - 1);
// Here's the JSL that convers the 1D answers back to 2D answers.
// use the 0-based blacklocs (previous statement), then add 1 to
// turn the 0-based results back into the 1-based indexes JMP expects.
rowlocs = Floor( (blacklocs) / nc ) + 1;
collocs = Mod( (blacklocs), nc ) + 1;
// Show the results
scale = 16; // try bigger or smaller scale for your screen size
New Window( "Example",
Graph Box(
// make the graph the same aspect ratio as the bitmap
framesize( nc * scale, nr * scale ),
// make the point marker size big; .65 is approximately right
<<MARKER size=""></MARKER></SETFONTSIZE>
Pixels from a bitmap, displayed as markers in a graphPixels from a bitmap, displayed as markers in a graph位圖中的像素,在圖表中顯示為標記
也可以看看: JSL 矩陣是什麼?有關 JMP 中矩陣的介紹。