필터 지우기
필터 지우기

implementing FOR LOOP for beginning and end

조회 수: 8 (최근 30일)
gabriele fadanelli
gabriele fadanelli 2020년 3월 27일
답변: Abhisek Pradhan 2020년 4월 2일
Hi everybody. I want to implement this code in which I would love to avoid for loop, but most of all I wish I could avoid putting out of the cycle the first and last values of the matrix rows.
freq=2; %just a frequency or a time
t_buckets=[1 5 8 90]; %vector of times upon which I am constructing my "buckets"
t=(1/freq:1/freq:t_buckets(end)); %building a time vector spaced with the frequency up to the last period in t_buckets
w_buck=zeros(length(t_buckets),length(t)); %initialize the matrix for my result, which are, as tu say, increasing vectors from zero up to a value of time then decreasing going to zero up to the next point in t_buckets
w_buck(1,1:freq*t_buckets(1))=1; %need to put this part out of the for loop
w_buck(1,freq*t_buckets(1)+1:freq*t_buckets(1+1))=(t(freq*t_buckets(1)+1:freq*t_buckets(2))-t_buckets(2))/(t_buckets(1)-t_buckets(2));
for i=2:length(t_buckets)-1 %recursive formula to get every row with necessary "bucket" values for times
w_buck(i,freq*t_buckets(i-1):freq*t_buckets(i)-1)=(t(freq*t_buckets(i-1):freq*t_buckets(i)-1)-t_buckets(i-1))/(t_buckets(i)-t_buckets(i-1));
w_buck(i,freq*t_buckets(i))=1;
w_buck(i,freq*t_buckets(i)+1:freq*t_buckets(i+1))=(t(freq*t_buckets(i)+1:freq*t_buckets(i+1))-t_buckets(i+1))/(t_buckets(i)-t_buckets(i+1));
end
%need to put last part out of the for loop otherwiae it doesn t work
w_buck(length(t_buckets),freq*t_buckets(end-1):freq*t_buckets(end)-1)=(t(freq*t_buckets(end-1):freq*t_buckets(end)-1)-t_buckets(end-1))/(t_buckets(end)-t_buckets(end-1));
w_buck(length(t_buckets),freq*t_buckets(length(t_buckets)))=1;
Now what I wish to do is first try to put everything in the same formula (i.e. the for loop in example) and then try to avoid this loop if possible.
Thanks to everyone who'll help me in simplifying
  댓글 수: 2
Guillaume
Guillaume 2020년 3월 27일
Can you explain what that code does? It's not very readable and if we first have to try to understand it, there's less chance you'll have an answer.
Writing comments in your code is essential!
gabriele fadanelli
gabriele fadanelli 2020년 3월 27일
Ok sorry I m a newbie, I ll do

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

채택된 답변

Abhisek Pradhan
Abhisek Pradhan 2020년 4월 2일
Use of FOR loop can be avoided in most of the cases using vectorization.
Refer the following link which has few examples on how to do vectorization.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by