Clear Filters
Clear Filters

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

3 views (last 30 days)
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

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 27 Jul 2023
Edited: Dyuman Joshi on 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

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!