how to get variable of function in for loop
3 ビュー (過去 30 日間)
古いコメントを表示
Hello, someone please help me.
I created a polynomial function f(x,y) using two variables. I varied the values of both variables to get the maximum f(x,y) using for loop and i got it. But, i dont know how to get or display the values of the x and y that made it. can you tell me the syntax to get them? thanks!!
x = 1:20;
y = 1:13;
f = [];
for i = 1:length(x), j = 1:length(j);
f(i,j) = x(i).^2 - x(i) -2*y(j).^2 + y(j) -25;
end
fmax = max(max(f));
display(fmax)
2 件のコメント
VBBV
2024 年 5 月 29 日
Do you mean display x and y values only or f values ?
x = 1:20 % delete the semi colon
y = 1:13 %
disp(x)
disp(y)
回答 (2 件)
Steven Lord
2024 年 5 月 29 日
Don't call max twice. Call max once with two output arguments and specify 'all' as the dimension over which to operate. That second output will be the linear index of the location where the maximum value returned as the first output was located. Then use ind2sub to get the row and column indices.
x = 1:20;
y = 1:13;
I've written your function as a function handle so I can call it from multiple places without retyping it.
fh = @(x, y) x.^2-x-2*y.^2+y-25;
Note that as originally written, this for loop doesn't do what you think it does. You can't have one for loop iterate over two arrays like this.
% f = [];
% for i = 1:length(x), j = 1:length(j);
% f(i,j) = fh(x(i), y(j));
% end
You need two for loops. Or you could use the vectorized approach others have suggested. But there's no need to grid the data explicitly as others have done; you can take advantage of the implicit expansion behavior of the basic operators in MATLAB like plus.
f = fh(x, y.')
[fmaxval, fmaxloc] = max(f, [], 'all')
What does that location of 248 correspond to in terms of x and y?
[row, col] = ind2sub(size(f), fmaxloc)
fprintf("Maximum of f is %d at x = %d, y = %d.\n", fmaxval, col, row)
Note that the index into x is the col index and the index into y is the row index. Let's check by evaluating the function once more at those specific values of x and y.
fh(x(col), y(row))
That matches the maximum value found by max (and by inspection of the displayed f array.)
0 件のコメント
VBBV
2024 年 5 月 29 日
x = 1:20;
y = 1:13;
f = [];
for i = 1:length(x),
for j = 1:length(y);
f(i,j) = x(i).^2 - x(i) -2*y(j).^2 + y(j) -25;
end
end
f
fmax = max(max(f));
display(fmax)
6 件のコメント
Akira Agata
2024 年 5 月 29 日
+1
x = 1:20;
y = 1:13;
% Create x- and y-grid
[xGrid, yGrid] = meshgrid(x, y);
% Calculate f
f = xGrid.^2 - xGrid - 2*(yGrid.^2) + yGrid -25;
% Find max(f) and it's linear index
[fmax, idx] = max(f(:));
% Show the result
sprintf('max(f) = %d', fmax)
sprintf('(x,y) = (%d, %d)', xGrid(idx), yGrid(idx))
% Visualize f
figure
surf(xGrid, yGrid, f)
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!