How can I use loops to perform different functions on every other array element?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello. If I want to create a column vector where I specify the value of the first element and then use loops to automatically generate values for the rest based on two different functions that are carried out alternatively until the vector is a specific size, how would I do this?
For instance, my input could be 100, and the code would generate a vector:
100
60
70
42
52
31.2
41.2
24.72
etc. for a given number of times where the two different functions are:
n = (n-1)*0.6
for all even values of n, and:
n = (n-1)+10
for all odd values of n apart from 1.
I'm sorry that I don't have any code to show but I am just starting with matlab and I honestly don't know where to start with this even after extensive googling.
Thank you in advance for helping :)
0 commentaires
Réponses (1)
Image Analyst
le 20 Avr 2019
Try this:
v = [100;60;70;42;52;31.2;41.2;24.72]
nOut = zeros(length(v), 1); % Instantiate column vector for output n.
for k = 1 : length(v)
if k == 1 || rem(k, 2) == 0
% It's even so use the even formula
nOut(k) = (k-1)*0.6; % For 1, 2, 4, 6, 8, ...
fprintf('For k = %d, we are using the even formula and the output = %f\n', k, nOut(k));
else
% It's odd so use the odd formula
nOut(k) = (k-1)+10; % For 3, 5, 7, ...
fprintf('For k = %d, we are using the odd formula and the output = %f\n', k, nOut(k));
end
end
% Show all values
nOut
You'll see in the command window:
For k = 1, we are using the even formula and the output = 0.000000
For k = 2, we are using the even formula and the output = 0.600000
For k = 3, we are using the odd formula and the output = 12.000000
For k = 4, we are using the even formula and the output = 1.800000
For k = 5, we are using the odd formula and the output = 14.000000
For k = 6, we are using the even formula and the output = 3.000000
For k = 7, we are using the odd formula and the output = 16.000000
For k = 8, we are using the even formula and the output = 4.200000
nOut =
0
0.6
12
1.8
14
3
16
4.2
2 commentaires
Voir également
Catégories
En savoir plus sur Historical Contests dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!