필터 지우기
필터 지우기

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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by