Effacer les filtres
Effacer les filtres

iteratively changing a value within a line of code based on the output

4 vues (au cours des 30 derniers jours)
James Rodriguez
James Rodriguez le 5 Avr 2021
Réponse apportée : Deepak le 23 Août 2024 à 9:32
I am having issues with the lines presented in the second section of the code below. I think it is inefficient to type it like this. Normally I would place all of the xn0,xn1...xn8 values into an array and then call the correspodning elements to be summed with the corresponding tc1 elements. However, I only know xn0 (although i can compute the rest) and therefore do not know how to approach this problem. Any help is greatly appreciaated.
(Sorry if the title was misleading I didnt know what to call this question. I also struggled to word it and hope the code can clarify my issue )
h1 =[0.6,0.617725,0.63545,0.653175,0.6709,0.688625,0.70635,0.724075];
h2 = [0.617725,0.63545,0.653175,0.6709,0.688625,0.70635,0.724075,0.7418];
fh1 = [276.981849374449,256.563282315502,233.338198927531,206.859609346339,176.571144087757,41.772230732072,101.568977010934,54.8034249508092]
fh2 = [256.563282315502,233.338198927531,206.859609346339,176.571144087757,41.772230732072,101.568977010934,54.8034249508092,-0.0508040527532690]
tc1 = ((h2-h1)./2).*(fh2+fh1);
xn0 = 0
%% I would prefer to be able to loop this such that xn1 replaces xn0, and then this is replaced by xn3 ,all while the column number is changing to
xn1 = xn0+tc1(:,1);
xn2 = xn1+tc1(:,2);
xn3 = xn2+tc1(:,3);
xn4 = xn3 +tc1(:,4);
xn5 = xn4 + tc1(:,5);% Continues on after this line (for each of the 8 columns in tc1)
%% My problem with using for loop
for i = [1:1:8]
xn1(i) = xn0+tc1(:,i) % This would just add each element from tc1 to xn0. I dont know how to get xn0 to change to xn1, and then that to the next etc
end

Réponses (1)

Deepak
Deepak le 23 Août 2024 à 9:32
Hi James, from my understanding, you have an array named tc1 of size 8, that stores double values. Now, you want to create another xn array whose values depend on tc1 array, and on previous index values of xn array.
To build the xn array, we can first initialize it with a default value. Then, we can iterate over it to calculate the values at each index. This way, we do need to fill in all the “xn” values manually.
Below is the MATLAB code for the same:
xn = zeros(1, length(tc1) + 1); % Initialize an array
xn(1) = 0; % Initial value for xn0
for i = 1:length(tc1)
xn(i + 1) = xn(i) + tc1(i);
end
Attaching the documentation of methods used for reference:
I hope this fixes the problem.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by