For loop in a for loop doesn't work

1 回表示 (過去 30 日間)
Nicola Caldognetto
Nicola Caldognetto 2017 年 11 月 4 日
回答済み: Nicola Caldognetto 2017 年 11 月 5 日
So I'm playing with audio data and I have created a script which downsamples an audio file. Now I'm trying to write a script that tries to recompose the original audio copying the value of the data lost with the downsampling. This is my script
prompt = 'Specific matrix ';
matrix = input(prompt); %audio matrix 1 column
prompt = 'Specific frequency destination ';
freqdest = input(prompt);
prompt = 'Specific frequency signal ';
frq = input(prompt);
sstep = freqdest/frq;
X=ones(length(matrix)*sstep,1); %creating the new matrix
for n=1:length(matrix) % n counter matrix total
for m=0:sstep-1
X(n+m)=matrix(n);
end
end
The inside for
for m=0:sstep-1
X(n+m)=matrix(n);
end
Seems not working at all. The script creates correctly the matrix with the right dimension but copy all the value of "matrix" in "X" without launch the script for every value. Why? Has someone a solution? Thanks

採用された回答

Nicola Caldognetto
Nicola Caldognetto 2017 年 11 月 5 日
for n=1:length(matrix) % n counter matrix total
for m=0:sstep-1
X(n+m+h)=matrix(n);
end
h=h+sstep-1;
end
This is the right loop

その他の回答 (3 件)

M
M 2017 年 11 月 4 日
You should be careful when manipulating matix.
M(i,j)
returns the value of the ith row and jth column of the matrix.
In your example you just give one argument to your matrices.
  2 件のコメント
Nicola Caldognetto
Nicola Caldognetto 2017 年 11 月 4 日
Yeah because my matrix has only one column. I have tried also with ,1 but it doesn't work
Walter Roberson
Walter Roberson 2017 年 11 月 4 日
That is okay. The comments indicate that it is a vector with one column.

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


Walter Roberson
Walter Roberson 2017 年 11 月 4 日
X(n+m)=matrix(m);
perhaps? You were always copying the same value, matrix(n)
  1 件のコメント
Nicola Caldognetto
Nicola Caldognetto 2017 年 11 月 5 日
yeah because the internal loop copy the same value for sstep times but when it ends it should go through the next n values, but it doesn't

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


Jan
Jan 2017 年 11 月 5 日
Use the debugger to find out, what's going on: Set a breakpoint inside the loop and step through the code line by line observing the values of the counters.
for n=1:length(matrix) % n counter matrix total
for m=0:sstep-1
X(n+m)=matrix(n);
end
end
Note that e.g. x(2) is assigned by n=1 and m=1 and by n=2 and m=2. Perhaps you want:
X = repmat(matrix, 1, sstep)
or
X = repelem(matrix, 1, sstep)
or perhaps the same with matrix(:) or a transposition.
  1 件のコメント
Nicola Caldognetto
Nicola Caldognetto 2017 年 11 月 5 日
Oh I found the bug thanks to your phrase "n=1 and m=1 and by n=2 and m=2" It's my logic error, I will fix it and post the correct code

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

カテゴリ

Help Center および File ExchangeAudio I/O and Waveform Generation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by