Help deal with the loop

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 Comments

Jon
Jon on 30 Jul 2019
I do not see in your code where you assign the variable y

Sign in to comment.

Answers (1)

Jon
Jon on 30 Jul 2019
Edited: Jon on 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 Comments

The array y is pre-set, just when I do without a loop, I get only one value (I suspect the latter)
y=uint32(0);
fileName='С:\FinalPlus.sl3';
fileID = fopen(fileName);
y=fread(fileID,[1,1],'uint32'); % y 1x100000 y=[7475555 ....]
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;
Canswer=x3*a-10.22;
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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Tags

Asked:

on 30 Jul 2019

Commented:

Jon
on 31 Jul 2019

Community Treasure Hunt

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

Start Hunting!