I have this in matlab
A=34;
for i =1:1:6
A = A + 1;
t1=fix(A/(2*32));
t2=fix((A-(t1*64))/(32));
t3=fix(((A-(t1*64)) - (t2*32))/(16));
G = [t1 t2 t3]
end
When it displays, it gives
G= 0 1 0
G= 0 1 0
G= 0 1 0 ....to the 6th G(the values are not right anyway)
but I want to have an output of
G1= 0 1 0
G2= 0 1 0
G3= 0 1 0....to G6
and then cat.or pu开发者_如何学Pythont them into a set of G = [G1, G2, G3, ...,G6].Please how do I get this done?
There are a few points to address regarding your question...
Preallocating arrays and matrix indexing:
If you want to save the values you generate on each iteration, you can preallocate the array G
as a 6-by-3 matrix of zeroes before your loop and then index into a given row of the matrix within your loop to store the values:
A = 34;
G = zeros(6, 3); % Make G a 6-by-3 matrix of zeroes
for i = 1:6
% Your calculations for t1, t2, and t3...
G(i, :) = [t1 t2 t3]; % Add the three values to row i
end
Vectorized operations:
In many cases you can avoid for loops altogether in MATLAB and often get a speed-up in your code by using vectorized operations. In your case, you can create a vector of values for A
and perform your calculations for t1
, t2
, and t3
on an element-wise basis using the arithmetic array operators .*
and ./
:
>> A = (35:40).'; %' Create a column vector with the numbers 35 through 40
>> t1 = fix(A./64); % Compute t1 for values in A
>> t2 = fix((A-t1.*64)./32); % Compute t2 for values in A and t1
>> t3 = fix((A-t1.*64-t2.*32)./16); % Compute t3 for values in A, t1, and t2
>> G = [t1 t2 t3] % Concatenate t1, t2, and t3 and display
G =
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
0 1 0
The bonus here is that G
will automatically end up as a 6-by-3 matrix containing all the values you want, so no preallocation or indexing is necessary.
Displaying output:
If you want to create formatted output that differs from the default display of numbers that occurs when you leave off the semicolon at the end of a line, you can use functions like fprintf
. For example, to get the output you want you could run this after creating G
as above:
>> fprintf('G%d = %d %d %d\n', [1:6; G.']) %' Values are drawn column-wise
G1 = 0 1 0 % from the second argument
G2 = 0 1 0
G3 = 0 1 0
G4 = 0 1 0
G5 = 0 1 0
G6 = 0 1 0
If I understood you correctly your problem is just the output (so that all values are stored in G), right?
You might try this:
lowerbound = (i-1)*3 + 1;
G(lowerbound:lowerbound + 2) = [t1 t2 t3]
This should expand G with the newly computed values
精彩评论