What's the problem with this simple anonymous function?

2 ビュー (過去 30 日間)
Muhammad Usman
Muhammad Usman 2021 年 11 月 10 日
コメント済み: Muhammad Usman 2021 年 12 月 7 日
Here's an simple code:
clear all; clc; close all;
n = 1:3;
for i = 1:numel(n) %numel is used if someother time I'll use negative values for n
f = @(x) x.^n;
fplot(f);
hold on;
f1 = @(x) x.^(1/n);
fplot(f1);
hold on;
end
The function "f" is running OK but "f1" is generating graphics error. For one value of n like:
f1 = @(x) x.^(1/2);
It generates the plot, but not in the loop.
Please let me know what's wrong?

採用された回答

Steven Lord
Steven Lord 2021 年 11 月 10 日
You likely meant to use n(i) in your functions, not n. Another option would be to use 1./n instead of 1/n.
n = 1:3
n = 1×3
1 2 3
y = 1./n
y = 1×3
1.0000 0.5000 0.3333
z = 1/n(2)
z = 0.5000
w = 1/n
Error using /
Matrix dimensions must agree.
  2 件のコメント
Muhammad Usman
Muhammad Usman 2021 年 12 月 7 日
Thanks, sometimes a simpler logic never clicks into the mind
Muhammad Usman
Muhammad Usman 2021 年 12 月 7 日
One thing more to ask how to adjust legend for array n
n = 1:10;
figure(1);
f = @(x) x.^n;
fplot(f);
hold on;
legend(sprintf('$x^{%d}$\n',n),'Interpreter','latex');
xlim([0 10])
The output I got:
How to correct it?
Thanks in advance

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by