How to create a loop in which a number increments and

조회 수: 28(최근 30일)
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

채택된 답변

Daniel Bridges
Daniel Bridges 2018년 2월 22일
편집: Daniel Bridges 2018년 2월 22일
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.
  댓글 수: 1
Blanca Rodriguez
Blanca Rodriguez 2018년 2월 23일
thank you i already fixed my problem

댓글을 달려면 로그인하십시오.

추가 답변(1개)

KSSV
KSSV 2018년 2월 22일
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,[]) ;

태그

Community Treasure Hunt

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

Start Hunting!

Translated by