Saving a new array from an old array

2 views (last 30 days)
dontdeimos
dontdeimos on 23 May 2015
Commented: Stephen23 on 23 May 2015
Hello,
This is my first program in Matlab. I had to normalize an array (which works) and then using that new array count the number of zero crossings.
I tried this by imbedding an if statement into a for-loop. It is supposed to multiply the first two numbers and if it is negative it adds to the new array, then so on until it has gone through the whole array. It's then supposed to print just the number of zero crossings; I tried this by using length of the array. However, this isn't working at all. I got this to work in a c program, but I'm having trouble translating it to Matlab.
Can anyone help with just the end of my program. I don't think the new array is saving. Here is my code:
inStr = input('Please enter file name: ', 's');
x = dlmread('data.txt','s');
sum = 0;
%Find the sum of the array
for i = 1:10,
sum = sum + x(i);
end
%Use the sum of the array to find the mean of the array
Mean = sum / 10;
%For loop to find the normalized array
for i = 1:10,
x(i) = x(i) - Mean;
end
disp('Normalized Mean Array: ')
disp(x)
%For loop and if statement to find the zero crossings.
y = 0;
for i = 1:1:9,
if (x(i) * x(i+1) < 0),
(y == x(1:10));
end
end
length(y);
disp('Number of zero crossings: ')
disp(y)
Thanks for your help!
  3 Comments
dontdeimos
dontdeimos on 23 May 2015
Edited: dontdeimos on 23 May 2015
Oh, that was something I was trying that was supposed to save a new array? It works in a c program so I decided to try it, I was running out of ideas. It was originally y == x(i)
Stephen23
Stephen23 on 23 May 2015
Why use loops to do this? MATLAB is not C! Here are the three most useful links for beginners (and also experienced programmers who are coming from low-level languages like C). Study them!

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 23 May 2015
Do you have to use for loops? Or just want to? I mean, why not vectorize it? Like
xNormalized = x - mean(x);
positiveElements = x > 0;
and so on using things like diff(sign(xNormalized)). Is this homework?

Tags

Community Treasure Hunt

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

Start Hunting!