Help deal with the loop
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Trying to create a loop for counting.
for i=1:length(y) % y = 1xn n=100000
a = 20.224124124124
b = 7664555.5789;
x1(i)=y(i)/b;
x2(i)=exp(double(x1(i));
x3(i)=(5 * sin(x2(i))) - (pi/2);
x4(i)=(10 * sin(x2(i))) - (pi/2);
Aansver(i)=x3(i) * a;
Bansver(i)=x4(i) * a;
end
in x1 constantly shows 1
what could be the problem? p.s. data y seven-digit numbers (example 7709998)
2 Kommentare
Antworten (1)
Jon
am 30 Jul. 2019
Bearbeitet: Jon
am 30 Jul. 2019
You do not need a loop to evaluate this type of expression in MATLAB. The beauty of MATLAB is it lets you do math directly with vectors and matrices without the need for loops and subscripts.
So for example in your case, assuming that your variable y is defined just as the numbers 1,2,3, ... 100000, you could use:
y = 1:100000;
a = 20.224124124124
b = 7664555.5789;
x1 = y/b;
x2 = exp(x1);
x3 = 5*sin(x2)-pi/2;
x4 = 10*sin(x2)-pi/2;
Aanswer = x2*a;
Banswer = x4*a;
Also, for future reference, if you do have to do math in a loop, do not put constants, e.g. a and b above, inside the loop. You are needlesly reaassigning them over and over. Also it is more efficient to "prealloacate your variables" before the loop begins. Please see https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
2 Kommentare
Jon
am 31 Jul. 2019
The problem is with your use of the fread function, you are only reading one value from the data file. The second argument you are giving to fread, [1,1], is telling it to only read an array of dimensions 1 row by 1 column. In other words, just one value.
Assuming that the only thing in C:\FinalPlus.s13 are values of the the variable that you will call y, then you can just use
y = fread(fileID)
and it will read all of them in.
If there are other variables besides y in the data file you will have to do a little more to separate them out.
If you haven't looked already, please see https://www.mathworks.com/help/matlab/ref/fread.html for more details on fread
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!