Error using inline subsref line 12 not enough inputs to inline function

Hi, I've been tested so many times and tried all the answers from here and still not working. if the expression is with m=4.541*TN*S0/T T=1:0.1:100 TN=70 S0=0.99 integration with simpson ...

Michelle Noah

  • Direct link to this question

 ⋮ 

  • Direct link to this question

Hi, I’ve been tested so many times and tried all the answers from here and still not working.

if the expression is

with

m=4.541*TN*S0/T

T=1:0.1:100

TN=70

S0=0.99

integration with simpson 1/3

here my code:

f1=inline(‘3/2*(cos(x)^2)*exp(m*(3/2*(cos(x)^2))-1/2)*sin(x)’,‘m’,‘x’);

f2=inline(‘exp(m*(3/2*(cos(x)^2)-1/2))’,‘m’,‘x’);

I1=(h/3)*(f1a+4*jumodd+2*jumeven+f1b);

I2=(h/3)*(f2c+4*jumodd+2*jumeven+f2d);

plot(S,T,‘ob-‘,‘linewidth’,3);

xlabel(‘S’,‘fontsize’,18);

ylabel(‘T’,‘fontsize’,18);

  4 Comments

Walter Roberson

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

What advantage do you see in using inline ? Have you benchmarked it for your situation and found it gives better performance? Have you found something using inline that you have not been able to express in other ways?

I ask because Mathworks has recommended against using inline() for roughly the last 18 years.

Michelle Noah

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Humm sorry, I don’t know any other way, and why is it inline? because, it’s already in my lecturer’s guide. And btw, any suggestion from you? I’m happy to try it

Stephen23

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

«it’s already in my lecturer’s guide.»

Your lecturer wrote their (mis)guide back in the dark ages. You should ask for your money back.

«And btw, any suggestion from you? I’m happy to try it»

You do what the MATLAB documentation recommends:

Walter Roberson

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

f1 = @(m,x) 3/2*(cos(x).^2).*exp(m.*(3/2*(cos(x).^2))-1/2).*sin(x);

f2 = @(m,x) exp(m.*(3/2*(cos(x).^2)-1/2));

Sign in to comment.

Accepted Answer

KSSV

  • Direct link to this answer

 ⋮ 

  • Direct link to this answer

These lines:

Should be:

As the functions f1, f2 need two inputs.

  5 Comments

Michelle Noah

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

another error appears: Unrecognized function or variable ‘f’.

thanks before

KSSV

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

It is because, there is no function with the name f. Either you have to define it or it could be a typo error for f1 or f2.

Michelle Noah

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

and 1 more, how can i define f as f1/f2?

Walter Roberson

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

f = @(m,x) f1(m,x)./f2(m,x);

Michelle Noah

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

okayy got it, thankyou so much @KSSV and @Walter Roberson 🙏

Sign in to comment.


More Answers (0)

See Also

Categories

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

MathWorks - Domain Selector

cfif

0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

1

Метод Адамса для решения дифференциальных уравнений

07.11.2016, 07:22. Показов 4525. Ответов 11

Метки нет (Все метки)


Написал программу для решения дифф. уравнения, не могу исправить ошибки. Помогите пожалуйста

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function test_adams_1
clc;
f=inline('1+y/x+exp(y/x)');
%Начало и конец промежутка решения
a=1;b=1.9;
%Число шагов
n=20;
%Шаг
h=(b-a)/n;
x=zeros(1,n+1);
y=zeros(1,n+1);
x=a:h:b;
%Присвоим первым 4 координатам вектора Y известные значения
y(1:4)=[0 0.0941 0.1967 0.3083];
[x' y']
F=zeros(1,4);
% F=feval(f,x(1:4),y(1:4));%так почему-то не получается вектор F
F(1)=feval(f,x(1),y(1));
F(2)=feval(f,x(2),y(2));
F(3)=feval(f,x(3),y(3));
F(4)=feval(f,x(4),y(4));
disp(F);
%Шаг
l=x(2)-x(1);
for i=4:n
    %Прогноз
    p=y(i)+(l/24)*(F*[-9 37 -59 55]');
    x(i+1)=x(1)+l*i;
    F=[F(2) F(3) f(4) feval(f,x(i+1),p)];
    %Корректор
    y(i+1)=y(i)+(l/24)*(F*[1 -5 19 9]')
    F(4)=feval(f,x(i+1),y(i+1));
end
% [x' y']

Выводит следующие ошибки:

это столбики с x и y (для y нужно только первые 4)
ans =

1.0000 0
1.0450 0.0941
1.0900 0.1967
1.1350 0.3083
1.1800 0
1.2250 0
1.2700 0
1.3150 0
1.3600 0
1.4050 0
1.4500 0
1.4950 0
1.5400 0
1.5850 0
1.6300 0
1.6750 0
1.7200 0
1.7650 0
1.8100 0
1.8550 0
1.9000 0

Вывод матрицы F

2.0000 2.1843 2.3782 2.5837

Error using inline/subsref (line 12)
Not enough inputs to inline function.

Error in test_adams_1 (line 30)
F=[F(2) F(3) f(4) feval(f,x(i+1),p)];

 Комментарий модератора 
ПОВТОРНОЕ нарушение Правил форума: 4.9. Используйте тэги форматирования текста и редактор формул для удобства восприятия ваших сообщений другими пользователями.

Добавлено через 16 часов 18 минут
как я понял — никто ничего предложить не может

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт по математике/физике

3368 / 1893 / 569

Регистрация: 09.04.2015

Сообщений: 5,297

07.11.2016, 08:10

2

Лучший ответ Сообщение было отмечено cfif как решение

Решение

Цитата
Сообщение от cfif
Посмотреть сообщение

f=inline(‘1+y/x+exp(y/x)’);

А почему Вы считаете, что при передаче параметров в эту функцию первым должен быть х, а вторым y?
Это наверно потому, что компьютер умный и сам догадается (возможно прочитает Ваши мыси) как надо правильно.

Не по теме:

В следующей теме Вы такую же виликую мудрость возложили на знатоков в этой теме и считаете, что они и без исходного кода сразу определят какую несусветную глупость Вы можете набить у себя накомпьюторе с помощью клавиатуры.

Цитата
Сообщение от cfif
Посмотреть сообщение

F=[F(2) F(3) f(4) feval(f,x(i+1),p)];

Вам похоже не ведомо, что MATLAB маленькие и большие буквы считает разными.

Цитата
Сообщение от cfif
Посмотреть сообщение

% F=feval(f,x(1:4),y(1:4));%так почему-то не получается вектор F

Тему про «пресловутую точку претыкания» Вам читатать наверно некогда.

Цитата
Сообщение от cfif
Посмотреть сообщение

это столбики с x и y (для y нужно только первые 4)

Но в 15 строке Вы же указали выводить все.



1



0 / 0 / 0

Регистрация: 07.11.2016

Сообщений: 1

07.11.2016, 08:22

3

А как понять кто должен быть первым при передаче в эту функцию?
F=feval(f,x(1:4),y(1:4)); как с этим разобраться?
Объясните пожалуйста



0



0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

07.11.2016, 08:47

 [ТС]

4

Цитата
Сообщение от SSC
Посмотреть сообщение

А почему Вы считаете, что при передаче параметров в эту функцию первым должен быть х, а вторым y?
Это наверно потому, что компьютер умный и сам догадается (возможно прочитает Ваши мыси) как надо правильно.

А как сделать так чтобы он меня понимал как надо?

Цитата
Сообщение от SSC
Посмотреть сообщение

Вам похоже не ведомо, что MATLAB маленькие и большие буквы считает разными.

Опечатался

Цитата
Сообщение от SSC
Посмотреть сообщение

Сообщение от cfif
% F=feval(f,x(1:4),y(1:4));%так почему-то не получается вектор F
Тему про «пресловутую точку претыкания» Вам читатать наверно некогда.

Подскажите пожалуйста как надо

Цитата
Сообщение от SSC
Посмотреть сообщение

Но в 15 строке Вы же указали выводить все.

Вывел я всё, но использую потом только первые 4

Добавлено через 10 минут

Цитата
Сообщение от cfif
Посмотреть сообщение

Error using inline/subsref (line 12)
Not enough inputs to inline function.

Как избавиться от этой ошибки



0



Эксперт по математике/физике

3368 / 1893 / 569

Регистрация: 09.04.2015

Сообщений: 5,297

07.11.2016, 08:53

5

Цитата
Сообщение от cfif
Посмотреть сообщение

А как сделать так чтобы он меня понимал как надо?

Посмотреть HELP по функции inline ( в MATLAB 2012b третий пример).

Цитата
Сообщение от cfif
Посмотреть сообщение

Подскажите пожалуйста как надо

Я же написал, прочитайте в головном разделе MATLAB на форуме тему «пресловутая точка претыкания», иначе почти в каждой Вашей программе будут такие проблемы.

Цитата
Сообщение от cfif
Посмотреть сообщение

Вывел я всё, но использую потом только первые 4

Ну и используйте на здоровье, откуда тогда вопрос

Цитата
Сообщение от cfif
Посмотреть сообщение

это столбики с x и y (для y нужно только первые 4)

Добавлено через 1 минуту
Scs, ответы на Ваши вопросы в предидущем моем ответе



1



0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

07.11.2016, 09:05

 [ТС]

6

Цитата
Сообщение от SSC
Посмотреть сообщение

Я же написал, прочитайте в головном разделе MATLAB на форуме тему «пресловутая точка претыкания», иначе почти в каждой Вашей программе будут такие проблемы.

Прочитал про «зловещую точка претыкания»

Цитата
Сообщение от cfif
Посмотреть сообщение

f=inline(‘1+y/x+exp(y/x)’);

Тут необходимо поставить 2 точки, правильно?



0



Эксперт по математике/физике

3368 / 1893 / 569

Регистрация: 09.04.2015

Сообщений: 5,297

07.11.2016, 09:09

7

Цитата
Сообщение от cfif
Посмотреть сообщение

Тут необходимо поставить 2 точки, правильно?

Да, перед знаком деления



1



0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

07.11.2016, 09:33

 [ТС]

8

Цитата
Сообщение от SSC
Посмотреть сообщение

Да, перед знаком деления

f=inline(‘1+y./x+exp(y./x)’);

Добавлено через 14 секунд
так?

Добавлено через 39 секунд

Цитата
Сообщение от cfif
Посмотреть сообщение

Error using inline/subsref (line 12)
Not enough inputs to inline function.

эта ошибка именно из-за этого и сплывает?

Добавлено через 7 минут
в ошибке написано, что не определены входные элементы

Добавлено через 14 минут
по этой ошибке похоже надо с этим разобраться:

Цитата
Сообщение от SSC
Посмотреть сообщение

Сообщение от cfif
А как сделать так чтобы он меня понимал как надо?

Цитата
Сообщение от SSC
Посмотреть сообщение

Посмотреть HELP по функции inline ( в MATLAB 2012b третий пример).



0



Эксперт по математике/физике

3368 / 1893 / 569

Регистрация: 09.04.2015

Сообщений: 5,297

07.11.2016, 09:34

9

Цитата
Сообщение от cfif
Посмотреть сообщение

так?

Да, точки то так, но где определение переменных.

Цитата
Сообщение от cfif
Посмотреть сообщение

эта ошибка именно из-за этого и сплывает?

Нет, это не поэтому.
У меня данной ошибки вообще нет, поэтому точной причины не назову.
В качестве рекомендации могу сказать что строки 10 и 12 несколько противоречат друг другу, поэтому строку 10 лучше убрать.



1



0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

07.11.2016, 09:37

 [ТС]

10

Цитата
Сообщение от SSC
Посмотреть сообщение

Да, точки то так, но где определение переменных.

x и y определены в качестве массива



0



Эксперт по математике/физике

3368 / 1893 / 569

Регистрация: 09.04.2015

Сообщений: 5,297

07.11.2016, 09:45

11

Цитата
Сообщение от cfif
Посмотреть сообщение

x и y определены в качестве массива

Я не про это.
Вы не посмотрели HELP по inline.
В Вашем вроде работает правильно и так, но это можно считать случайностью (наверно просто потому что x стоит раньше y в кодировке алфавита), а программирование надо вести точно.



1



0 / 0 / 0

Регистрация: 30.11.2015

Сообщений: 33

07.11.2016, 10:00

 [ТС]

12

Ошибку не выдаёт, всё хорошо. Спасибо большое за консультацию!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

07.11.2016, 10:00

12

Содержание

  1. Why is there error?
  2. Direct link to this question
  3. Direct link to this question
  4. Direct link to this comment
  5. Direct link to this comment
  6. Accepted Answer
  7. Direct link to this answer
  8. Direct link to this answer
  9. More Answers (0)
  10. See Also
  11. Categories
  12. Community Treasure Hunt
  13. How to Get Best Site Performance
  14. Americas
  15. Europe
  16. Asia Pacific
  17. Error using exp matlab
  18. Examples
  19. Numeric Representation of e
  20. Euler’s Identity
  21. Plot Exponential Function
  22. Input Arguments
  23. X — Input array scalar | vector | matrix | multidimensional array
  24. Output Arguments
  25. Y — Exponential values scalar | vector | matrix | multidimensional array
  26. Extended Capabilities
  27. Tall Arrays Calculate with arrays that have more rows than fit in memory.
  28. C/C++ Code Generation Generate C and C++ code using MATLAB® Coder™.
  29. GPU Code Generation Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
  30. Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
  31. GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
  32. Distributed Arrays Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.
  33. Error using exp matlab
  34. Examples
  35. Numeric Representation of e
  36. Euler’s Identity
  37. Plot Exponential Function
  38. Input Arguments
  39. X — Input array scalar | vector | matrix | multidimensional array
  40. Output Arguments
  41. Y — Exponential values scalar | vector | matrix | multidimensional array
  42. Extended Capabilities
  43. Tall Arrays Calculate with arrays that have more rows than fit in memory.
  44. C/C++ Code Generation Generate C and C++ code using MATLAB® Coder™.
  45. GPU Code Generation Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
  46. Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
  47. GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
  48. Distributed Arrays Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.
  49. Error using inline/subsref (line 13) Not enough inputs to inline function.
  50. Direct link to this question
  51. Direct link to this question
  52. Accepted Answer
  53. Direct link to this answer
  54. Direct link to this answer
  55. Direct link to this comment
  56. Direct link to this comment
  57. More Answers (0)
  58. See Also
  59. Categories
  60. Community Treasure Hunt
  61. How to Get Best Site Performance
  62. Americas
  63. Europe
  64. Asia Pacific
  65. Документация
  66. Синтаксис
  67. Описание
  68. Примеры
  69. Числовое Представление e
  70. Идентичность Эйлера
  71. Графическое изображение показательной функции
  72. Входные параметры
  73. X — Входной массив скаляр | вектор | матрица | многомерный массив
  74. Выходные аргументы
  75. Y — Экспоненциальные значения скаляр | вектор | матрица | многомерный массив
  76. Расширенные возможности
  77. «Высокие» массивы Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.
  78. Генерация кода C/C++ Генерация кода C и C++ с помощью MATLAB® Coder™.
  79. Генерация кода графического процессора Сгенерируйте код CUDA® для NVIDIA® графические процессоры с помощью GPU Coder™.
  80. Основанная на потоке среда Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool .
  81. Массивы графического процессора Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
  82. Распределенные массивы Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.
  83. Смотрите также
  84. Открытый пример
  85. Документация MATLAB
  86. Поддержка

Why is there error?

Direct link to this question

Direct link to this question

1 Comment

Accepted Answer

Direct link to this answer

Direct link to this answer

0 Comments

More Answers (0)

See Also

Categories

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

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

Error using exp matlab

Y = exp( X ) returns the exponential e x for each element in array X . For complex elements z = x + iy , it returns the complex exponential

e z = e x ( cos y + i sin y ) .

Use expm to compute a matrix exponential.

Examples

Numeric Representation of e

Calculate the exponential of 1, which is Euler’s number, e .

Euler’s Identity

Euler’s identity is the equality e i π + 1 = 0 .

Compute the value of e i π .

Plot Exponential Function

Plot y = e x / 2 for x values in the range [ — 2 , 1 0 ] .

Input Arguments

X — Input array
scalar | vector | matrix | multidimensional array

Input array, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: single | double
Complex Number Support: Yes

Output Arguments

Y — Exponential values
scalar | vector | matrix | multidimensional array

Exponential values, returned as a scalar, vector, matrix, or multidimensional array.

For real values of X in the interval (- Inf , Inf ), Y is in the interval ( 0 , Inf ). For complex values of X , Y is complex. The data type of Y is the same as that of X .

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For more information, see Tall Arrays.

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox) .

Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox) .

Источник

Error using exp matlab

Y = exp( X ) returns the exponential e x for each element in array X . For complex elements z = x + iy , it returns the complex exponential

e z = e x ( cos y + i sin y ) .

Use expm to compute a matrix exponential.

Examples

Numeric Representation of e

Calculate the exponential of 1, which is Euler’s number, e .

Euler’s Identity

Euler’s identity is the equality e i π + 1 = 0 .

Compute the value of e i π .

Plot Exponential Function

Plot y = e x / 2 for x values in the range [ — 2 , 1 0 ] .

Input Arguments

X — Input array
scalar | vector | matrix | multidimensional array

Input array, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: single | double
Complex Number Support: Yes

Output Arguments

Y — Exponential values
scalar | vector | matrix | multidimensional array

Exponential values, returned as a scalar, vector, matrix, or multidimensional array.

For real values of X in the interval (- Inf , Inf ), Y is in the interval ( 0 , Inf ). For complex values of X , Y is complex. The data type of Y is the same as that of X .

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For more information, see Tall Arrays.

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox) .

Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox) .

Источник

Error using inline/subsref (line 13) Not enough inputs to inline function.

Direct link to this question

Direct link to this question

0 Comments

Accepted Answer

Direct link to this answer

Direct link to this answer

1 Comment

More Answers (0)

See Also

Categories

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

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

Документация

Синтаксис

Описание

Y = exp( X ) возвращает экспоненциальный e x для каждого элемента в массиве X . Для комплексных элементов z = x + iy , это возвращает комплексную экпоненту

e z = e x ( cos y + i sin y ) .

Используйте expm вычислить матричный экспоненциал.

Примеры

Числовое Представление e

Вычислите экспоненциал 1, который является номером Эйлера, e .

Идентичность Эйлера

Идентичность Эйлера является равенством e i π + 1 = 0 .

Вычислите значение e i π .

Графическое изображение показательной функции

График y = e x / 2 для x значения в области значений [ — 2 , 1 0 ] .

Входные параметры

X — Входной массив
скаляр | вектор | матрица | многомерный массив

Входной массив, заданный как скалярный, векторный, матричный или многомерный массив.

Типы данных: single | double
Поддержка комплексного числа: Да

Выходные аргументы

Y — Экспоненциальные значения
скаляр | вектор | матрица | многомерный массив

Экспоненциальные значения, возвращенные как скаляр, вектор, матрица или многомерный массив.

Для вещественных значений X в интервале (- Inf Inf Y находится в интервале ( 0 Inf ). Для комплексных чисел X Y является комплексным. Тип данных Y совпадает с тем из X .

Расширенные возможности

«Высокие» массивы
Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.

Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.

Генерация кода графического процессора
Сгенерируйте код CUDA® для NVIDIA® графические процессоры с помощью GPU Coder™.

Основанная на потоке среда
Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool .

Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.

Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.

Эта функция полностью поддерживает массивы графического процессора. Для получения дополнительной информации смотрите функции MATLAB Запуска на графическом процессоре (Parallel Computing Toolbox) .

Распределенные массивы
Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.

Эта функция полностью поддерживает распределенные массивы. Для получения дополнительной информации смотрите функции MATLAB Запуска с Распределенными Массивами (Parallel Computing Toolbox) .

Смотрите также

Открытый пример

У вас есть модифицированная версия этого примера. Вы хотите открыть этот пример со своими редактированиями?

Документация MATLAB

Поддержка

© 1994-2021 The MathWorks, Inc.

1. Если смысл перевода понятен, то лучше оставьте как есть и не придирайтесь к словам, синонимам и тому подобному. О вкусах не спорим.

2. Не дополняйте перевод комментариями “от себя”. В исправлении не должно появляться дополнительных смыслов и комментариев, отсутствующих в оригинале. Такие правки не получится интегрировать в алгоритме автоматического перевода.

3. Сохраняйте структуру оригинального текста — например, не разбивайте одно предложение на два.

4. Не имеет смысла однотипное исправление перевода какого-то термина во всех предложениях. Исправляйте только в одном месте. Когда Вашу правку одобрят, это исправление будет алгоритмически распространено и на другие части документации.

5. По иным вопросам, например если надо исправить заблокированное для перевода слово, обратитесь к редакторам через форму технической поддержки.

Источник

I appreciate your time.

x1,x2 are changing each loop.

dF1: I just differentiate F separately, outside the program.

I will send you all the program. do not wary about all the steps. the problem occurred because of f=inline(‘g’,’h’). I just want to make f as a function of h which i need to find the minimum of f(h), but i can not write h separately I should substitute x3 and x4 which are function of x1,h and x2,h. respectively.

The code is********************

x1=-4; x2=5;

F=inline(‘4*(sqrt(x1^2 + (10-x2)^2 )-10)^2 + 0.5*(sqrt(x1^2 + (10+x2)^2 )-10)^2 -5*(x1+x2)’,’x1′,’x2′);

E_n=100; E_t=10^-3;Tol=10^-10;

for j=1:200

dF1=(8*(sqrt(x1^2 + (10-x2)^2) — 10) * x1 )/sqrt(x1^2 + (10-x2)^2) +((1*(sqrt(x1^2 + (10+x2)^2) — 10) * x1 )/sqrt(x1^2 + (10+x2)^2)) — 5 ;

dF2=((8*(sqrt(x1^2 + (10-x2)^2) — 10)*(x2-10)) / (sqrt(x1^2 + (10-x2)^2))) + (((sqrt(x1^2 + (10+x2)^2) — 10)*(10+x2))/(sqrt(x1^2 + (10+x2)^2))) — 5 ;

s1=-dF1;

s2=-dF2;

x3=x1+s1*h;

x4=x2+s2*h;

% now i want to set g as function of h

g=4*(sqrt(x3^2 + (10-x4)^2 )-10)^2 + 0.5*(sqrt(x3^2 + (10+x4)^2)-10)^2 -5*(x3+x2);

f=inline(‘g’,’h’);

% Finding the bounds on the minimum of the function

%values of the initial bounds [a,b]=[0.0,0.1]

a(1)=0.0;

b(1)=0.1;

r=0.61803;

GSR=1.61803; %Golden Section Ratio = (r/r-1)

c(1)=r*a(1)+(1-r)*b(1); % c is a point between [a,b]

for i=1:100

if if f(a(i))>f(c(i)) && f(b(i))>f(c(i))

% This means there is a minimum value of the function f in the interval [a,b]

break;

else

%since the slope is negative we will shift the interval to the right by

%using the previous values of ‘c’ and ‘b’ and the Golden Section Ratio GSR

a(i+1)=c(i); c(i+1)=b(i);

%b can be determined from {(b-c/c-a)=(r/r-1)=GSR, then

b(i+1)=c(i+1)*(1+GSR)-(GSR*a(i+1));

end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Reduction of original interval using the golden section algorithm.

a(1)=a(i); b(1)=b(i);

c(1)=r*a(1)+(1-r)*b(1);

d(1)=(1-r)*a(1)+r*b(1);% c and d are points between [a,b]

for n=1:100

if f(c(n))<=f(d(n))

a(n+1)=a(n);

b(n+1)=d(n);

d(n+1)=c(n);

c(n+1)=r*a(n+1)+(1-r)*b(n+1);

else

if f(c(n))>f(d(n))

a(n+1)=c(n);

b(n+1)=b(n);

c(n+1)=d(n);

d(n+1)=(1-r)*a(n+1)+r*b(n+1);

end

end

E_n=abs((b(n+1)-a(n+1))/(b(1)-a(1)));

if E_n < E_t;

break

end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%cubic plunomyal fit to the points obtained at the last iteration

X1=a(n+1);X2=c(n+1);X3=d(n+1);X4=b(n+1);

q1=X3^3*(X2-X1)-X2^3*(X3-X1)+X1^3*(X3-X2);

q2=X4^3*(X2-X1)-X2^3*(X4-X1)+X1^3*(X4-X2);

q3=(X3-X2)*(X2-X1)*(X3-X1);

q4=(X4-X2)*(X2-X1)*(X4-X1);

q5=f(X3)*(X2-X1)-f(X2)*(X3-X1)+f(X1)*(X3-X2);

q6=f(X4)*(X2-X1)-f(X2)*(X4-X1)+f(X1)*(X4-X2);

a3=(q3*q6-q4*q5)/(q2*q3-q1*q4);

a2=(q5-a3*q1)/q3;

a1=((f(X2)-f(X1))/(X2-X1))-(a3*((X2^3-X1^3)/(X2-X1)))-a2*(X1+X2);

a0=f(X1)-a1*X1-a2*X1^2-a3*X1^3;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% finding the minimum

delta=a2^2-(3*a1*a3);

XI=(sqrt(delta)-a2)/(3*a3); XII=(-a2-sqrt(delta))/(3*a3);

if f(XI)<= f(XII)

h=XI;

else

h=XII;

end

x3=x1+s1*h;

x4=x2+s2*h;% we already used this in lines 11,12 for g=f(h)

if abs(F(x3,x4)-F(x1,x2)) <= 10^-10

break;

end

if j==5

break;

end

x1=x3;

x2=x4;

end

disp(‘f(x1,x2) x1 x2 iteration’);

m=[F(x1,x2),x1,x2,j];

disp(m);

  •  
  • matlab

  •  04-08-2022
  •  | 

  •  

Question

I am trying to run this simple MATLAB routine. which will plot a window function.

M = 26;
n = [0:(M-1)];
om = linspace(-pi, pi, 201); % for displaying frequency response  
oc = pi/6; % cutoff frequency
% desired impulse response:
hd = inline('1*(abs(om) < oc)', 'om', 'oc');
stem(n, hd, 'filled')
axis([0 M-1 -0.1, 0.3]), xlabel 'n', ylabel 'h[n]'

But i am getting the following error

??? Error using ==> inline.subsref at 14
Not enough inputs to inline function.

Error in ==> xychk at 80
if isvectorY, y = y(:); end

Error in ==> stem at 43
[msg,x,y] = xychk(args{1:nargs},’plot’);

i feel inline function has enough inputs . but error says no.
Any help would be appreciated.

EDIT # 1

so i learned how to use anonymous function and hopefully used it correctly but now i am having another little error. Here is the edited code.

 M = 26;
n = [0:(M-1)];
om = linspace(-pi, pi, 201); % for displaying frequency response  
oc = pi/6; % cutoff frequency
% desired impulse response:
hd = @(om,oc) 1*abs(om) < oc;
hn = hd(om,oc);
stem(n, hn, 'filled')
axis([0 M-1 -0.1, 0.3]), xlabel 'n', ylabel 'h[n]'

i get the error X must be same length as Y in stem. I get the point. But i cant understand how to make n and hn of equal length. n is from -pi to + pi i am sure. but isnt hd also from -pi to + pi. Also can you tell how to make it from -pi to pi if it isnt already.

No correct solution

OTHER TIPS

The issue here is that stem doesn’t know the value of oc and om when it tries to get y-values from your inline function.

In general, it is preferable to use anonymous functions instead of inlines (also since inlines will be obsolete in the future):

hd = @(x,y) 1*abs(x)<y;

stem(n,hd(om,oc),'filled') %# this is also how you should call stem if you use the inline

The @(...) part defines how many inputs the function takes; the part after than states the function of the two inputs. Note that you can have additional variables appearing in the function definition. Their values are fixed at the time the anonymous function is defined.

The output is a function like e.g. sin, and can be called as such.

Понравилась статья? Поделить с друзьями:
  • Error using imhist expected input number 1 i or x to be two dimensional
  • Error using horzcat dimensions of matrices being concatenated are not consistent матлаб
  • Error username is already in use please choose another one
  • Error user with this e mail already exist
  • Error user with such email already exists