matlab自帶的線性索引轉換下標函數必須指定下標個數,也就是數據的維度。這在實際應用中受到了限制。
(什麼是線性索引,什麼是下標,不再介紹,相信你如果搜到了本貼,必然知道這兩個概念)
% 原函數:
% 原函數可以直接拷貝到matlab中,生成m函數使用。
% 重寫一個由線性索引查找下標的函數,適合多維,輸出數組代表下標
% matlab 自帶輸出結果必須指定下標個數,此處無需指定
function subarray = myind2sub(datasize, ind)
% input: datasize 數據尺寸
% ind 數據線性索引 整數
% output: subarray 數組形式的下標索引
% suozi 2016.05.17 HIT
% 379786867 [email protected]
% ind 判斷
if ind ~= fix(ind)
disp('輸入的索引必須爲整數')
return
end
subarray = zeros(size(datasize));
rest = ind;
i=length(datasize);
while i > 0
if i ~= 1
tmpdivide = rest/prod(datasize(1:i-1));
if tmpdivide == fix(tmpdivide) % 餘數爲0
subarray(i) = tmpdivide;
else
subarray(i) = floor(tmpdivide) + 1;
end
tmprest = rest - (subarray(i) - 1)*prod(datasize(1:i-1));
if tmprest ~= 0
rest = tmprest;
% else rest = rest;
end
else
subarray(i) = rest;
end
i = i - 1;
end
end
如果函數有漏洞或錯誤,請指正。
示例:
example1:
>> A = rand(5,5)
A =
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
>> subarray = myind2sub(size(A), 10)
subarray =
5 2
example2:
>> A = rand(3,4,2)
A(:,:,1) =
0.7577 0.6555 0.0318 0.0971
0.7431 0.1712 0.2769 0.8235
0.3922 0.7060 0.0462 0.6948
A(:,:,2) =
0.3171 0.4387 0.7952 0.4456
0.9502 0.3816 0.1869 0.6463
0.0344 0.7655 0.4898 0.7094
>> subarray = myind2sub(size(A), 10)
subarray =
1 4 1
>>