Using a for-loop with several input matrices

2 次查看(过去 30 天)
I have several matrices that I want to run a for-loop through, and am not sure how to do this.
clc
clear all
TEST1 = [0 0 0 0];
TEST2 = [1, 1, 1, 1];
TEST3 = [235.0623 188.2428 44.9479 103.4551];
l = length(TEST3);
for k = 1:l
y(k) = 0;
if (k==1)
w(k) = 1/sqrt(l);
else
w(k) = sqrt(2/l);
end
for n = 1:l
y(k) = y(k)+TEST3(n)*cos(pi*(2*n-1)*(k-1)/(2*l));
end
y(k) = y(k)*w(k);
end
DCTTEST3 = (y)
My for-loop works well, and is currently programmed to use test3 matrix as the input, and show the corresponding matrix output.
Is it possible, without triplicating the code, to use this format but run the three test cases through it, and then have three output matrices? If it is, can you please show me how?
Thanks in advance! Chris

回答(1 个)

Jan
Jan 2017-4-17
TestSet = {[0 0 0 0], ...
[1, 1, 1, 1], ...
[235.0623 188.2428 44.9479 103.4551]};
DCTTEST = cell(1, numel(TestSet)); % Pre-allocate
for iTest = 1:numel(TestSet)
Test = TestSet{iTest};
l = length(Test);
y = zeros(1, l); % Pre-allocate
w = zeros(1, l);
for k = 1:l
if (k==1)
w(k) = 1/sqrt(l);
else
w(k) = sqrt(2/l);
end
for n = 1:l
y(k) = y(k) + Test(n) * cos(pi * (2 * n-1) * (k-1) / (2*l));
end
y(k) = y(k)*w(k);
end
DCTTEST{iTest} = y;
end
  2 个评论
Chris Matthews
Chris Matthews 2017-4-18
编辑:Chris Matthews 2017-4-18
When i look at DCTTEST, it only shows this:
DCTTEST =
[1x4 double] [1x4 double] [1x4 double]
And when I look at each of these vectors, they all only show the answer from the third test case?
Jan
Jan 2017-4-18
Use the debugger to see, what's going on. If this does not reveal the problem, post your code here.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by