How to store values in a vector?
Afficher commentaires plus anciens
I want to define an empty vector, and then fill it up with some values, the result of a for loop, such as,
function test2()
C = 5
F = 9
for i = 1:3
A = 1+3
B = 3+4
C = 5+6
end
end
The result of this function is 11 values, I need to put them in a vector where its size is 11. the result is: C= 5 F= 9 A = 4 B = 7 C = 11 A = 4 B = 7 C = 11 A = 4 B = 7 C = 11
I need that all those values are stored in a vector.
Vet= 5 9 4 7 11 4 7 11 4 7 11
I would be very grateful if you could help me. Thans.
1 commentaire
@Smache Meriem: your example is far to specific to be useful. Please explain what you are actually trying to achieve. For example, nothing changes inside your loop, so it is not clear why you bother having a loop at all. Nor is it clear why you don't just define the vector using the values that you have given.
Réponses (1)
Adam
le 29 Juil 2016
Vet = [5 9 repmat( [1+3, 3+4, 5+6], [1 3] )]
will give you that specific vector. For a more general case it depends what you want to do though.
8 commentaires
MS
le 29 Juil 2016
Adam
le 29 Juil 2016
Please give an example in the original question that shows the full complexity of the problem.
There is no point to giving an over-generalised solution to a trivial problem, but if the example you give is too simple then the solution given is likely to be too simple too!
MS
le 29 Juil 2016
Adam
le 29 Juil 2016
vet = zeros( 1, 12 );
vet(1:2) = [byte_Plaintext_initial, byte_key_initial];
for i_test = 1:2
idxStep = ( i_test - 1 ) * 5;
...
vet( 3 + idxStep ) = round_middle_start(NumByte);
...
vet( 4 + idxStep ) = round_middle_s_box(NumByte);
...
...
vet( 7 + idxStep ) = round_middle_k_sch(NumByte);
...
end
will probably do the job, with the rest of your code in amongst that, but it isn't a nice solution. The problem for that lies before the point you showed really where you already have all these different variable names that you now want to put into a single vector.
MS
le 29 Juil 2016
Guillaume
le 29 Juil 2016
A cleaner solution would be to refactor the loop body into its own function:
function out = somegoodfunctionname(i_test, round, NumByte)
%I assume that round is a variable shadowing matlab round function (not a good idea)
round_middle_start= dec2hex(round (i_test).start)
%... rest of code
byte_k_sch= round_middle_k_sch(NumByte)
out = [byte_start, byte_s_box, byte_s_row, byte_m_col];
end
The body of your main function then becomes:
%...
round_key_intial=dec2hex (key)
byte_key_initial=round_key_intial(NumByte)
vet = arrayfun(@(i_test) somegoodfunctionname(i_test, round, NumByte), ...
1:2, 'UniformOutput', false);
vet = [byte_Plaintext_initial, byte_key_initial, vet{:}];
Much cleaner overall
MS
le 29 Juil 2016
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!