フィルターのクリア

How do I find indexes of three for-loops of maximum value of function with three indexes?

3 ビュー (過去 30 日間)
clear all
clc
xx=0:1:5;
yy=0:1:7;
zz=-5:1:1;
for i=1:length(xx)
x=xx(i);
for j=1:length(yy)
y=yy(j);
for k=1:length(zz)
z=zz(k);
w(k,j,i)=x^2-y^3+z;
end
end
end

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 7 月 27 日
編集済み: Dyuman Joshi 2023 年 7 月 28 日
The MATLAB approach to generate the output would be -
(Edit - corrected some typos)
xx=0:1:5;
yy=0:1:7;
zz=-5:1:1;
%Note that the order of input to ndgrid() is according to the indices
%of w in the for loop - (k,j,i)
[Z,Y,X]=ndgrid(zz,yy,xx);
W = X.^2 - Y.^3 + Z;
%Get the maximum value in W and the corresponding linear index
[maxval,maxidx] = max(W,[],'all')
maxval = 26
maxidx = 287
%Get the indices for each dimension via ind2sub()
[ix,jx,kx]=ind2sub(size(W),maxidx)
ix = 7
jx = 1
kx = 6
Note that max will return the linear index that corresponds to the first occurence of maximum in the array.
%Comparison for the output obtained from ndgrid
for i=1:length(xx)
x=xx(i);
for j=1:length(yy)
y=yy(j);
for k=1:length(zz)
z=zz(k);
w(k,j,i)=x^2-y^3+z;
end
end
end
isequal(W,w)
ans = logical
1

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by