-
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
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.
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
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:
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
-
Direct link to this answer
⋮
-
Direct link to this answer
These lines:
Should be:
As the functions f1, f2 need two inputs.
5 Comments
Direct link to this comment
⋮
-
Link
Direct link to this comment
another error appears: Unrecognized function or variable ‘f’.
thanks before
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.
Direct link to this comment
⋮
-
Link
Direct link to this comment
and 1 more, how can i define f as f1/f2?
Direct link to this comment
⋮
-
Link
Direct link to this comment
f = @(m,x) f1(m,x)./f2(m,x);
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.
cfif 0 / 0 / 0 Регистрация: 30.11.2015 Сообщений: 33 |
|||||||||
1 |
|||||||||
Метод Адамса для решения дифференциальных уравнений07.11.2016, 07:22. Показов 4525. Ответов 11 Метки нет (Все метки)
Написал программу для решения дифф. уравнения, не могу исправить ошибки. Помогите пожалуйста
Выводит следующие ошибки: это столбики с x и y (для y нужно только первые 4) 1.0000 0 Вывод матрицы F 2.0000 2.1843 2.3782 2.5837 Error using inline/subsref (line 12) Error in test_adams_1 (line 30)
Добавлено через 16 часов 18 минут
__________________
0 |
3368 / 1893 / 569 Регистрация: 09.04.2015 Сообщений: 5,297 |
|
07.11.2016, 08:10 |
2 |
Решение
f=inline(‘1+y/x+exp(y/x)’); А почему Вы считаете, что при передаче параметров в эту функцию первым должен быть х, а вторым y? Не по теме: В следующей теме Вы такую же виликую мудрость возложили на знатоков в этой теме и считаете, что они и без исходного кода сразу определят какую несусветную глупость Вы можете набить у себя накомпьюторе с помощью клавиатуры.
F=[F(2) F(3) f(4) feval(f,x(i+1),p)]; Вам похоже не ведомо, что MATLAB маленькие и большие буквы считает разными.
% F=feval(f,x(1:4),y(1:4));%так почему-то не получается вектор F Тему про «пресловутую точку претыкания» Вам читатать наверно некогда.
это столбики с x и y (для y нужно только первые 4) Но в 15 строке Вы же указали выводить все.
1 |
0 / 0 / 0 Регистрация: 07.11.2016 Сообщений: 1 |
|
07.11.2016, 08:22 |
3 |
А как понять кто должен быть первым при передаче в эту функцию?
0 |
0 / 0 / 0 Регистрация: 30.11.2015 Сообщений: 33 |
|
07.11.2016, 08:47 [ТС] |
4 |
А почему Вы считаете, что при передаче параметров в эту функцию первым должен быть х, а вторым y? А как сделать так чтобы он меня понимал как надо?
Вам похоже не ведомо, что MATLAB маленькие и большие буквы считает разными. Опечатался
Сообщение от cfif Подскажите пожалуйста как надо
Но в 15 строке Вы же указали выводить все. Вывел я всё, но использую потом только первые 4 Добавлено через 10 минут
Error using inline/subsref (line 12) Как избавиться от этой ошибки
0 |
3368 / 1893 / 569 Регистрация: 09.04.2015 Сообщений: 5,297 |
|
07.11.2016, 08:53 |
5 |
А как сделать так чтобы он меня понимал как надо? Посмотреть HELP по функции inline ( в MATLAB 2012b третий пример).
Подскажите пожалуйста как надо Я же написал, прочитайте в головном разделе MATLAB на форуме тему «пресловутая точка претыкания», иначе почти в каждой Вашей программе будут такие проблемы.
Вывел я всё, но использую потом только первые 4 Ну и используйте на здоровье, откуда тогда вопрос
это столбики с x и y (для y нужно только первые 4) Добавлено через 1 минуту
1 |
0 / 0 / 0 Регистрация: 30.11.2015 Сообщений: 33 |
|
07.11.2016, 09:05 [ТС] |
6 |
Я же написал, прочитайте в головном разделе MATLAB на форуме тему «пресловутая точка претыкания», иначе почти в каждой Вашей программе будут такие проблемы. Прочитал про «зловещую точка претыкания»
f=inline(‘1+y/x+exp(y/x)’); Тут необходимо поставить 2 точки, правильно?
0 |
3368 / 1893 / 569 Регистрация: 09.04.2015 Сообщений: 5,297 |
|
07.11.2016, 09:09 |
7 |
Тут необходимо поставить 2 точки, правильно? Да, перед знаком деления
1 |
0 / 0 / 0 Регистрация: 30.11.2015 Сообщений: 33 |
|
07.11.2016, 09:33 [ТС] |
8 |
Да, перед знаком деления f=inline(‘1+y./x+exp(y./x)’); Добавлено через 14 секунд Добавлено через 39 секунд
Error using inline/subsref (line 12) эта ошибка именно из-за этого и сплывает? Добавлено через 7 минут Добавлено через 14 минут
Сообщение от cfif
Посмотреть HELP по функции inline ( в MATLAB 2012b третий пример).
0 |
3368 / 1893 / 569 Регистрация: 09.04.2015 Сообщений: 5,297 |
|
07.11.2016, 09:34 |
9 |
так? Да, точки то так, но где определение переменных.
эта ошибка именно из-за этого и сплывает? Нет, это не поэтому.
1 |
0 / 0 / 0 Регистрация: 30.11.2015 Сообщений: 33 |
|
07.11.2016, 09:37 [ТС] |
10 |
Да, точки то так, но где определение переменных. x и y определены в качестве массива
0 |
3368 / 1893 / 569 Регистрация: 09.04.2015 Сообщений: 5,297 |
|
07.11.2016, 09:45 |
11 |
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 |
Содержание
- Why is there error?
- Direct link to this question
- Direct link to this question
- Direct link to this comment
- Direct link to this comment
- Accepted Answer
- Direct link to this answer
- Direct link to this answer
- More Answers (0)
- See Also
- Categories
- Community Treasure Hunt
- How to Get Best Site Performance
- Americas
- Europe
- Asia Pacific
- Error using exp matlab
- Examples
- Numeric Representation of e
- Euler’s Identity
- Plot Exponential Function
- Input Arguments
- X — Input array scalar | vector | matrix | multidimensional array
- Output Arguments
- Y — Exponential values scalar | vector | matrix | multidimensional array
- Extended Capabilities
- Tall Arrays Calculate with arrays that have more rows than fit in memory.
- 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 .
- GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
- Distributed Arrays Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.
- Error using exp matlab
- Examples
- Numeric Representation of e
- Euler’s Identity
- Plot Exponential Function
- Input Arguments
- X — Input array scalar | vector | matrix | multidimensional array
- Output Arguments
- Y — Exponential values scalar | vector | matrix | multidimensional array
- Extended Capabilities
- Tall Arrays Calculate with arrays that have more rows than fit in memory.
- 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 .
- GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
- Distributed Arrays Partition large arrays across the combined memory of your cluster using 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
- Accepted Answer
- Direct link to this answer
- Direct link to this answer
- Direct link to this comment
- Direct link to this comment
- More Answers (0)
- See Also
- Categories
- Community Treasure Hunt
- How to Get Best Site Performance
- Americas
- Europe
- Asia Pacific
- Документация
- Синтаксис
- Описание
- Примеры
- Числовое Представление e
- Идентичность Эйлера
- Графическое изображение показательной функции
- Входные параметры
- X — Входной массив скаляр | вектор | матрица | многомерный массив
- Выходные аргументы
- Y — Экспоненциальные значения скаляр | вектор | матрица | многомерный массив
- Расширенные возможности
- «Высокие» массивы Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.
- Генерация кода C/C++ Генерация кода C и C++ с помощью MATLAB® Coder™.
- Генерация кода графического процессора Сгенерируйте код CUDA® для NVIDIA® графические процессоры с помощью GPU Coder™.
- Основанная на потоке среда Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool .
- Массивы графического процессора Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
- Распределенные массивы Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.
- Смотрите также
- Открытый пример
- Документация MATLAB
- Поддержка
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(:); endError 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.