Function returns scalar independent of input, but I need a matrix output

6 ビュー (過去 30 日間)
DB
DB 2022 年 3 月 30 日
コメント済み: DB 2022 年 3 月 31 日
I have function handle f:
f = @(x)4.3206303272e-05.*x(1).^2+2.39837699915e-05.*x(2).^2
Where x is a vector. I want to plot the mesh of this function, but each input returns a scalar. For example:
f([1 0]) = 4.3206e-05
f([1:4 5:7]) = 1.3914e-04
f3([rand(3) rand(3)]) = 5.3729e-06
How come, and how can I change this?
I came to a function handle because of this: Link
  2 件のコメント
Torsten
Torsten 2022 年 3 月 30 日
編集済み: Torsten 2022 年 3 月 30 日
Use arrayfun.
Or make a simple loop over the (x/y) combinations for which you want to evaluate the handle.
In the form given, the handle only accepts x to be a single vector, not a vector of vectors, since x(1) and x(2) are indexed.
DB
DB 2022 年 3 月 31 日
I did not understand how to apply arrayfun. However, using a double for loop worked, and I got the mesh grid as desired! Thank you so much!

サインインしてコメントする。

回答 (1 件)

KSSV
KSSV 2022 年 3 月 30 日
clc; clear all ;
f = @(x1, x2)4.3206303272e-05.*x1.^2+2.39837699915e-05.*x2.^2 ;
f(1,0)
ans = 4.3206e-05
f([1:4]', [5:8]')
ans = 4×1
0.0006 0.0010 0.0016 0.0022
f(rand(3,1),rand(3,1))
ans = 3×1
1.0e-04 * 0.3743 0.2474 0.1337
  1 件のコメント
DB
DB 2022 年 3 月 31 日
Yes but I have x as a 2x1 vector, and not x1 and x2, and I cannot seem to rewrite it to this. Furthermore, shouldn't it be possible with just a vector x? I mean it would take a lot of lines if you have a lot of variables.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by