Help with loops _ multiple variables

2 ビュー (過去 30 日間)
Maddison Wagner
Maddison Wagner 2018 年 11 月 11 日
編集済み: Stephen23 2018 年 11 月 12 日
I’ve been trying to write a loop where the below equations will take place for each of the 4 values in the arrays below ie x1 is first calculated with the first value of each and then calculated with the 2nd values of each, etc. I keep getting a result that moves to the end of the loop and repeats the calculation for x1 using all variables instead of just the appropriate variable of each array. Not expecting someone to write the code but an example using loops for several variables and arrays would be great .
Sm1= [2;3;1;4];
Fc1 = [5;2;3;7];
A1= [1;4;1;2];
Fs = 60;
t1 = (0:sm1-1)/Fs;
x1 = A1*cos(2*pi*Fc1*t1);
For sm1(1:end)
t1 = (0:sm1-1)/Fs;
End
For A1(1:end
For Fc1(1:end)
x1 = A1*cos(2*pi*Fc1*t1);
End
End

採用された回答

Stephen23
Stephen23 2018 年 11 月 11 日
編集済み: Stephen23 2018 年 11 月 11 日
Use indexing and vectorize the appropriate operations:
Sm1 = [2;3;1;4];
Fc1 = [5;2;3;7];
A1 = [1;4;1;2];
Fs = 60;
N = numel(A1);
C = cell(1,N); % optional.
for k = 1:N
t1 = (0:Sm1(k)-1)/Fs
x1 = A1(k).*cos(2*pi*Fc1(k)*t1)
... your code here
C{k} = x1; % optional: store the vector x1.
end
  2 件のコメント
Maddison Wagner
Maddison Wagner 2018 年 11 月 12 日
編集済み: Stephen23 2018 年 11 月 12 日
Thank you! When I create the matrix from each vector of x1, I’m attempting to concatenate each x1 value into a single column , I accomplished this with
for k = 1:N
t1 = (0:Sm1(k)-1)/Fs
x1= A1(k).*cos(2*pi*Fc1(k)*t1)
M(:,k)= x1'
end
u = numel(M)
f = zeros(u,total_col)
f(:,colnum) = cat(1,M(:,1),M(:,2))
f(:,(1:6)~=colnum) = zeros %unused columns are zeros
But I’m looking to do this for any possible number of x1 arrays, so I attempted f(:,colnum) = cat(1,M(:,1(1:end))) But this did not work.
Stephen23
Stephen23 2018 年 11 月 12 日
編集済み: Stephen23 2018 年 11 月 12 日
"...I’m attempting to concatenate each x1 value into a single column..."
The easiest way to get one single column as the output is to collect the intermediate vectors into the cell array, and concatenate them after the loop:
C = cell(1,N);
for k = 1:N
...
C{k} = x1(:);
end
V = vertcat(C{:});
Gives:
>> V
V =
1.00000
0.86603
4.00000
3.91259
3.65418
1.00000
2.00000
1.48629
0.20906
-1.17557
Read more about how that concatenation works:

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

その他の回答 (1 件)

madhan ravi
madhan ravi 2018 年 11 月 11 日
"Not expecting someone to write the code but an example using loops for several variables and arrays would be great"

カテゴリ

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