Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Dyuman Joshi
Dyuman Joshi am 27 Jul. 2023
Bearbeitet: Dyuman Joshi am 28 Jul. 2023
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

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by