Square wave by vector multiplication

2 ビュー (過去 30 日間)
David
David 2024 年 3 月 30 日
編集済み: Voss 2024 年 4 月 1 日
I'm trying to build a square wave by using vector multiplication instead of using the "for" loop. It was suggested as multiply a 1xn vector with a nx1 vector. Here is my code constructing the square wave using the "for" loop:
N = 13;
f = 1000 * sin(2 * pi / (49 * N));
t = 0:0.0001:1;
n = 100;
A = 2;
square_wave = zeros(size(t));
for k = 1:n
if mod(k, 4) == 1
a_k = 4 * A / (k * pi);
elseif mod(k, 4) == 3
a_k = -4 * A / (k * pi);
else
a_k = 0;
end
square_wave = square_wave + a_k * cos(k * 2 * pi * f * t);
end
plot(t, square_wave);
xlabel('Time (s)');
ylabel('Amplitude');
title('Square Wave Approximation');
grid on

採用された回答

Voss
Voss 2024 年 3 月 30 日
k = (1:n).';
a_k = repmat([1;0;-1;0],n/4,1)*4*A./(k*pi);
square_wave = sum(a_k .* cos(k .* 2 * pi * f * t),1);
  2 件のコメント
David
David 2024 年 4 月 1 日
I tried to run the code above and it is reported error:
Error using .*
Matrix dimensions must agree.
square_wave = sum(a_k .* cos(k .* 2 * pi * f * t),1);
I assume the dimension of two matrices is not suitable for multiplication.
Do you have any idea how to fix this?
Voss
Voss 2024 年 4 月 1 日
編集済み: Voss 2024 年 4 月 1 日
This runs for me:
N = 13;
f = 1000 * sin(2 * pi / (49 * N));
t = 0:0.0001:1;
n = 100;
A = 2;
k = (1:n).';
a_k = repmat([1;0;-1;0],n/4,1)*4*A./(k*pi);
square_wave = sum(a_k .* cos(k .* 2 * pi * f * t),1);
plot(t, square_wave)
Double-check that you are running the same code.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by