How to create a loop in which a number increments and

6 visualizaciones (últimos 30 días)
Here's what I want to do: I have certain data plotted, let's say a cos function. I want to give matlab a certain value, example: 5 and from the whole function I want it to divide it in 5 equal sections. And then I want to get the media of each of those 5 equally spaced sections, or the variance or whatever. I know how to get all of the data, and I know how to calculate it separately.
I was doing it like this (manually): y=x(1:50)
prom=mean(y)
But i want to assign variables so when I want the spaces to go 5 or 10 or 100, i just need to change the variable.
I don't know if I am making myself clear

Respuesta aceptada

Daniel Bridges
Daniel Bridges el 22 de Feb. de 2018
Editada: Daniel Bridges el 22 de Feb. de 2018
Have you tried searching and browsing the MathWorks documentation? It seems like linspace could be used effectively here...
I think more generally, you just need to think logically about what you want done and then tell the computer to do it step by step. For example, thinking about what you say, I come up with the following script:
x = 1:100;
y = cos(x);
plot(x,y)
NoData = length(y);
NoSections = 5;
DataPerSection = NoData / NoSections;
result = zeros(1,NoSections);
counter = 1;
for loop = 1:NoSections
result(loop) = mean(y(counter:counter+DataPerSection-1));
counter = counter + DataPerSection; % advance to next chunk
end
Then you can just change the number of sections, NoSections to some number ... but you'd need to be careful that it divides the data into an integer or the for loop will have an error.

Más respuestas (1)

KSSV
KSSV el 22 de Feb. de 2018
N = 100 ; % should be multiple of the number of parts you want
th = linspace(0,2*pi) ;
y = cos(th) ;
plot(th,y)
% divide the section into 5 equal parts
th1 = reshape(th,5,[]) ;
y1 = reshape(y,5,[]) ;

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by