How to create a loop in which a number increments and
6 次查看(过去 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
0 个评论
采纳的回答
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 个)
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,[]) ;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!