I'm trying to create a script that populates an array by loopung through each pulse frequency 0-50Hz and its duty cycle 0-100%
The sequence should look like this:
Freq Duty Cycle
1.00 0
1.01 0
1.02 0
...
1.00 1
1.01 1
1.02 1
...
1.00 2
1.01 2
1.02 2
I have the for
loop for the first part:
T = [];
num_of_values=0
for freq = 1:.01:2
num_of_values = num_of_values 1;
T = [T; num_of_values freq]; %append to table
end
Which gives me:
1 1.00
2 1.01
3 2.02
...
Note: I added an increment in the beginning to see how many numbers are created.
I'm having trouble with attaching the duty cycle for
loop in the loop.
Also is there away to vectorize this to not use explicit loops?
I tried adding the duty cycle for
loop here but I don't get the output I'm trying to get:
T = [];
num_of_values = 0
for freq = 1:.01:2
num_of_values = num_of_values 1;
for duty_cycle = 0:1:2
end
T = [T; num_of_values freq duty_cycle]; %append to table
end
CodePudding user response:
The duty cycle loop should be outside, then you loop through the frequency inside. You should be able to invert the column order in the matrix without inverting the loop order.
Like this:
T=[];
duty_cycle=0
num_of_values=0
for duty_cycle = 0:1:100
for freq = 1:.01:2
num_of_values=num_of_values 1;
T=[T;num_of_values duty_cycle freq]; %append to table
end
end
T(1:5, :)
T(100:105, :)
T(200:205, :)
Result:
ans =
1.0000 1.0000 0
2.0000 1.0100 0
3.0000 1.0200 0
4.0000 1.0300 0
5.0000 1.0400 0
ans =
100.0000 1.9900 0
101.0000 2.0000 0
102.0000 1.0000 1.0000
103.0000 1.0100 1.0000
104.0000 1.0200 1.0000
105.0000 1.0300 1.0000
ans =
200.0000 1.9800 1.0000
201.0000 1.9900 1.0000
202.0000 2.0000 1.0000
203.0000 1.0000 2.0000
204.0000 1.0100 2.0000
205.0000 1.0200 2.0000
CodePudding user response:
You really shouldn't make a habit of reallocating an array of known size in a loop.
The first column is just the repetition of the frequency N times. Say N is 100, for each duty cycle. You can compute that with repmat
or kron
. The second column is the N duty cycles, each one repeated for the frequencies, which you can compute with kron
.
f = [0:0.01:50]';
ds = [0:100]';
m = numel(f);
n = numel(ds);
result = [repmat(f, n, 1) kron(ds, ones(m, 1))]