Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Dyuman Joshi
Dyuman Joshi el 27 de Jul. de 2023
Editada: Dyuman Joshi el 28 de Jul. de 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

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by