フィルターのクリア

Creating a set of equations programmatically

1 回表示 (過去 30 日間)
Lennart Vogt
Lennart Vogt 2018 年 10 月 22 日
コメント済み: Lennart Vogt 2018 年 10 月 23 日
I am trying to create a set of terms programmatically in order to build up a set of equations later in the code. The equations are supposed to be stored in Q. The vectors a and b are fixed parameters and vector T is the unknown variable.
n = 5;
a = [6 5 4 3 2 1];
b = [1 2 3 4 5 6];
L = 3;
k = 1;
while k<=n
Q{k,1} = @(T) a(k)*b(k)/L*(T(k+1)-T(k));
k = k+1;
end
Q
What happens when I run the code is that the information in k is passed in the index of Q (so that the terms are stored in different rows) but not in the index of a,b and T:
Q =
5×1 cell array
{@(T)a(k)*b(k)/L*(T(k+1)-T(k))}
{@(T)a(k)*b(k)/L*(T(k+1)-T(k))}
{@(T)a(k)*b(k)/L*(T(k+1)-T(k))}
{@(T)a(k)*b(k)/L*(T(k+1)-T(k))}
{@(T)a(k)*b(k)/L*(T(k+1)-T(k))}
For my purpose I'd like to get an output like this:
Q =
5×1 cell array
{@(T)a(1)*b(1)/L*(T(2)-T(1))}
{@(T)a(2)*b(2)/L*(T(3)-T(2))}
{@(T)a(3)*b(3)/L*(T(4)-T(3))}
{@(T)a(4)*b(4)/L*(T(5)-T(4))}
{@(T)a(5)*b(5)/L*(T(6)-T(5))}
Does anyone have an idea how to get this output?
  3 件のコメント
Matt J
Matt J 2018 年 10 月 23 日
That would be true only if you plan to change a and b later.
Lennart Vogt
Lennart Vogt 2018 年 10 月 23 日
Yes, you are right. My bad.

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

採用された回答

Matt J
Matt J 2018 年 10 月 22 日
編集済み: Matt J 2018 年 10 月 22 日
Your code already works fine. Each anonymous function Q{k} will use a different value for k, even if that isn't printed to the screen.
  1 件のコメント
Lennart Vogt
Lennart Vogt 2018 年 10 月 22 日
Alright thanks!

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

その他の回答 (1 件)

Adam Danz
Adam Danz 2018 年 10 月 22 日
編集済み: Adam Danz 2018 年 10 月 22 日
See Matt J's response. This solution will print the values you described by uses sprintf() and str2func().
n = 5;
a = [6 5 4 3 2 1];
b = [1 2 3 4 5 6];
L = 3;
k = 1;
while k<=n
Q{k,1} = str2func(sprintf('@(T) a(%d)*b(%d)/L*(T(%d)-T(%d));', k,k,k+1,k));
k = k+1;
end
  1 件のコメント
Lennart Vogt
Lennart Vogt 2018 年 10 月 22 日
Thank you, this is very helpful, too.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by