フィルターのクリア

Automatically set number of outputs of the gradient function

2 ビュー (過去 30 日間)
tiwwexx
tiwwexx 2023 年 8 月 24 日
コメント済み: tiwwexx 2023 年 8 月 29 日
I have a loss function I define to minimize some gradient magnitude. However, the dimension of my input data will change so I want to make my gradient have a generalized output. I have something close to a solution but Dont know how to get rid of the hard coded 2nd line below.
grad_vec = zeros([size(DATA),numel(size(DATA))]);
[grad_vec(:,:,:,1),grad_vec(:,:,:,2),grad_vec(:,:,:,3)] = gradient(DATA);
grad_mag = (sum(abs(grad_vec).^n,numel(size(DATA)))).^(1/n);
  3 件のコメント
Bruno Luong
Bruno Luong 2023 年 8 月 24 日
it probably miss a second colon on lhs
if numel(size(DATA))==2
[grad_vec(:,:,1),grad_vec(:,:,2)] = gradient(DATA);
...

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

採用された回答

Bruno Luong
Bruno Luong 2023 年 8 月 24 日
編集済み: Bruno Luong 2023 年 8 月 24 日
A = rand(10,10,10);
% This works for any dimensions of A
if isvector(A) % EDIT
N = 1;
else
N = ndims(A); % 3 in this example
end
G = cell(1,N);
[G{:}] = gradient(A);
G = cat(N+1,G{:});
size(G)
ans = 1×4
10 10 10 3
p = 2; % whatever power in >=1
Gmag = sum(abs(G).^p,N+1).^(1/p);
size(Gmag)
ans = 1×3
10 10 10
  3 件のコメント
Bruno Luong
Bruno Luong 2023 年 8 月 29 日
編集済み: Bruno Luong 2023 年 8 月 29 日
Not only it's good but it's also correct.
FYI you accept an answer from @Star Strider that is not correct (it ignores all the partial derivatives wrt to dimension > 1)
tiwwexx
tiwwexx 2023 年 8 月 29 日
Good catch

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by