Calculate this matrix in a more general and shorter way

2 ビュー (過去 30 日間)
Rowan Humphreys
Rowan Humphreys 2021 年 11 月 25 日
コメント済み: Rowan Humphreys 2021 年 11 月 30 日
Is there a way of generating P in a way that doesn't involve writing sin/cos/sin/cos repeatedly? Perhaps like how you can generate an array by writing 'x = 1:0.1:10'?
the size of 'x' is 100by1 and 'w' is some constant.
P=[ones(size(x)),cos(w*x),sin(w*x),cos(2*w*x),sin(2*w*x),cos(3*w*x),sin(3*w*x),cos(4*w*x),sin(4*w*x),cos(5*w*x),sin(5*w*x)]

回答 (2 件)

Stephen23
Stephen23 2021 年 11 月 25 日
x = rand(100,1);
w = pi;
m = (1:5).*w.*x;
m = [ones(100,1),reshape([cos(m);sin(m)],100,[])];
for comparison:
P = [ones(size(x)),cos(w*x),sin(w*x),cos(2*w*x),sin(2*w*x),cos(3*w*x),sin(3*w*x),cos(4*w*x),sin(4*w*x),cos(5*w*x),sin(5*w*x)];
isequal(P,m)
ans = logical
1
  1 件のコメント
Rowan Humphreys
Rowan Humphreys 2021 年 11 月 30 日
Thank you! This worked instantly :)

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


John D'Errico
John D'Errico 2021 年 11 月 25 日
x is 100x1. Now, suppose we want to generate multiple terms of the form sin(k*w*x), so k will be a vector. w is a fixed constant. Do you know how to do that?
x = (0:2:10)'; % arbitrary, your x is what you have. I've made x small so you can see what happens
w = 1; % again, my choice.
k = 1:4;
Ok, so what does this do in MATLAB?
x*w*k
ans = 6×4
0 0 0 0 2 4 6 8 4 8 12 16 6 12 18 24 8 16 24 32 10 20 30 40
This is just effectively a multiplication table. But do you see that it forms what you need? You can now compute sin(x*w*k), and cos(x*w*k).
In your case, x is a column vector, of size 100x1. Your code might look like:
x = ???? % whatever x is
w = ???? % again
n = 10; % how many terms?
P = [ones(size(x)),sin(x*w*k),cos(x*w*k)];
Now, the only problem is, all the sin terms are bundled together, then all the cos terms. If that bothers you, then reshuffle those columns. Something like this should work.
P(:,[2:2:end,3:2:end]) = P(:,[2:n+1,n+2:end]);
Now the sin and cos terms alternate.
  1 件のコメント
Rowan Humphreys
Rowan Humphreys 2021 年 11 月 30 日
Thank you John! I really apprecaite this!

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

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by