f



For loop while loop

I need to evaluate a function from 0:200 then create an 
array of every 5th value in the 0:200 array using a for 
loop then using a while loop.

I can't get the for loop to work at all because I cannot 
use >,< controllers, only an =.

So I focused on the While loop:

n=0:200;%creates 201 cell array from 0-200
x=n.^2+.25;%calculates x
plotcol=(length(n)-1)/5;%=(201-1)/5=40
y=zeros(1,plotcol);%creates 1X40 vector
col=1;%used for incrementing in while loop
while col<=plotcol;
      y(1,col)=x(1,5*col);
      col=col+1;
end

Unfortunately the output starts at 16 when it should start 
at 0. It seems like it should work to me, but something is 
messed up. Any help would be appreciated.
0
mpl (7)
9/18/2007 4:36:25 PM
comp.soft-sys.matlab 211266 articles. 15 followers. lunamoonmoon (258) is leader. Post Follow

4 Replies
1004 Views

Similar Articles

[PageSpeed] 51

"mpl " <mpl@mathworks.com> writes:

> I need to evaluate a function from 0:200 then create an 
> array of every 5th value in the 0:200 array using a for 
> loop then using a while loop.
>
> I can't get the for loop to work at all because I cannot 
> use >,< controllers, only an =.
>
> So I focused on the While loop:
>
> n=0:200;%creates 201 cell array from 0-200
> x=n.^2+.25;%calculates x
> plotcol=(length(n)-1)/5;%=(201-1)/5=40
> y=zeros(1,plotcol);%creates 1X40 vector
> col=1;%used for incrementing in while loop
> while col<=plotcol;
>       y(1,col)=x(1,5*col);
>       col=col+1;
> end
>
> Unfortunately the output starts at 16 when it should start 
> at 0. It seems like it should work to me, but something is 
> messed up. Any help would be appreciated.

Mentally trace this through.

The first element: col=1
Plugging it in: y(1,1) = x(1,5*1)

x(1,5) is 4.^2+.25, or 16.25

So now if you want the first element of y to be something OTHER than
the 5th element of x, modify your code appropriately.

-Peter
0
boettcher (2304)
9/18/2007 4:45:26 PM
"mpl " <mpl@mathworks.com> wrote in message <fcouq9
$7ch$1@fred.mathworks.com>...
> I need to evaluate a function from 0:200 then create an 
> array of every 5th value in the 0:200 array using a for 
> loop then using a while loop.
> 
> I can't get the for loop to work at all because I cannot 
> use >,< controllers, only an =.
> 
> So I focused on the While loop:
> 
> n=0:200;%creates 201 cell array from 0-200
> x=n.^2+.25;%calculates x
> plotcol=(length(n)-1)/5;%=(201-1)/5=40
> y=zeros(1,plotcol);%creates 1X40 vector
> col=1;%used for incrementing in while loop
> while col<=plotcol;
>       y(1,col)=x(1,5*col);
>       col=col+1;
> end
> 
> Unfortunately the output starts at 16 when it should 
start 
> at 0. It seems like it should work to me, but something 
is 
> messed up. Any help would be appreciated.

why not?
y=x(1:5:end);


0
dave7881 (1211)
9/18/2007 4:53:51 PM
Thanks again Peter! I have been looking at this stuff too 
long!

n=0:200;
x=n.^2+.25;
plotcol=(length(n)-1)/5;%=40
y=zeros(1,plotcol);%creates 1X40 vector
y(1,1)=x(1);
col=1;%used for incrementing
while col<=plotcol;
      y(1,col+1)=x(1,5*col);
      col=col+1;
end

> why not?
> y=x(1:5:end);
> 
> 
David,
That would be the easy way:) The instructions are to 
calculate all 201 values of x then plot only every 5th. 
This way would only calculate every 5th.

Now I have to plot this thing...I may be back:)
Many Many Thanks!

0
mpl (7)
9/18/2007 5:04:38 PM
"mpl " <mpl@mathworks.com> wrote in message <fcp0f5
$3er$1@fred.mathworks.com>...
> Thanks again Peter! I have been looking at this stuff 
too 
> long!
> 
> n=0:200;
> x=n.^2+.25;
> plotcol=(length(n)-1)/5;%=40
> y=zeros(1,plotcol);%creates 1X40 vector
> y(1,1)=x(1);
> col=1;%used for incrementing
> while col<=plotcol;
>       y(1,col+1)=x(1,5*col);
>       col=col+1;
> end
> 
> > why not?
> > y=x(1:5:end);
> > 
> > 
> David,
> That would be the easy way:) The instructions are to 
> calculate all 201 values of x then plot only every 5th. 
> This way would only calculate every 5th.
> 
> Now I have to plot this thing...I may be back:)
> Many Many Thanks!
> 

not if you leave it like this:

n=0:200;
x=n.^2+.25;
y=x(1:5:end);


0
dave7881 (1211)
9/18/2007 5:43:40 PM
Reply:

Similar Artilces:

WHILE LOOP AS FOR LOOP
its possible? For each id in (SELECT * FROM table) INSERT INTO table2(id,fk,nombre) values(1,id,'xxx'); Jessica Gonz�lez (jess.rgm@gmail.com) writes: > its possible? > > For each id in (SELECT * FROM table) > INSERT INTO table2(id,fk,nombre) > values(1,id,'xxx'); > So in SQL, you don't normally code the loops explicitly - the loops are hidden on the inside. Logically, it is an operation of a set. INSERT table(id, fk, nombre) SELECT 1, id, 'xxx' FROM table -- Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se Books Online for SQL Server 2005 at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx thanks.. but SET IDENTITY_INSERT table ON; INSERT INTO table(pk,activo,permiso,rol) SELECT IDENT_CURRENT('table')+1,'S',id, 1 FROM table2 return error Violation of PRIMARY KEY constraint 'PK__table__3213E83F2B947552'. Cannot insert duplicate key in object 'table'. The duplicate key value is (6). only 'id' i need get from table2 Jessica Gonz�lez (jess.rgm@gmail.com) writes: > thanks.. but > > SET IDENTITY_INSERT table ON; > INSERT INTO table(pk,activo,permiso,rol) > SELECT IDENT_CURRENT('table')+1,'S',id, 1 > ...

while loop in a while loop
Hi All, I have the following situation: while(rs.next()) { //loop1 while(rs2.next()) { //loop 2 } } It seems like loop 2 is only beeing used once. Should I after loop2 put the cursor back to the beginning? if so, how do I do that? Thanks! -- Posted by news://news.nb.nu Steven wrote: > Hi All, > > I have the following situation: > > > while(rs.next()) { //loop1 > > while(rs2.next()) { > //loop 2 > } > > } > The architypal loop (for a List eg ArrayList of Blah objects) is: for(It...

for loop into for loop.
Hello this is my first time that i am writing here.. I need your help to improve my code. This is my code for a=1:numberOfShortestPaths for b=a+1:a+numberOfShortestPaths for c=b+1:b+numberOfShortestPaths for d=c+1:c+numberOfShortestPaths for e=d+1:d+numberOfShortestPaths total_weight=weight(:,:,a)+weight(:,:,b)+weight(:,:,c)+weight(:,:,d)+weight(:,:,e); maximum=max(total_weight); end end end end end i want to do this function "automatically" because the letters ...

loops in loops
In the attached vi, the one second loop runs at one second and can't be touched.&nbsp; In the ten second loop, the ten second clock is a stand in for a process that generates a finished signal. The problem is once the process is complete, to start it again, leave the one second loop running, and start an additional process that will take less time than 10 seconds. thanks internal loops.vi: http://forums.ni.com/attachments/ni/170/319512/1/internal loops.vi Hi exo, what do you try there? If you start your vi, the value from your stop button will be read and after that, both loops "one" second and "ten" second won�t notice the state change of the stop button. Can you please explain, what you try to do?? Mike Okay, let me try again. I need three loops. Two loops start at the same time one runs fast one runs slow. The slow one is probably independent to the problem. When the second loop is done, it needs to restart and start a third loop that takes less than the second. You have a very basic dataflow problems. Unfortunately, I don't understand your description. &nbsp; I would recommend starting with some basic LabVIEW tutorials. &nbsp; Here are some&nbsp;obvious mistakes: - Your loop cannot read changes in the stop button, because the terminal is outside the loop. - You reset "internal loop" to zero in parallel to the loops. You cannot guarantee that this will happen before the locals are read so you might have a race c...

FOR loop not looping
I have the below script that uses 2 for loops. for some reason they loop is not looping ! /bin/ksh CURR_PATH='/main/nedcor/flexcube' cd $CURR_PATH for DIR1 in 'WIP' 'INPUT';do echo $DIR1 for DIR in $(find . -name $DIR1);do RESULT=`ls -A $DIR | egrep -v "BKUP|BKP"` echo $DIR echo $RESULT echo $RESULT1 if [ -z "$RESULT" ] ; then echo "No Files found" exit 0 else echo file $RESULT found exit 1 ...

Triple nested loop python (While loop insde of for loop inside of while loop)
try to make my triple nested loop working. My code would be: c = 4 y1 = [] m1 = [] std1 = [] while c <24: c = c + 1 a = [] f.seek(0,0) for columns in ( raw.strip().split() for raw in f ): a.append(columns[c]) x = np.array(a, float) not_nan = np.logical_not(np.isnan(x)) indices = np.arange(len(x)) interp = interp1d(indices[not_nan], x[not_nan], kind = 'nearest') p = interp(indices) N = len(p) dt = 900.0 #Time step (seconds) fs = 1./dt #Sampling frequency KA,PSD = oned_Fourierspectrum(p,dt) # Call Song's 1D FS function time_axis = np.linspace(0.0,N,num = N,endpoint = False)*15/(60*24) plot_freq = 24*3600.*KA #Convert to cycles per day plot_period = 1.0/plot_freq # convert to days/cycle fpsd = plot_freq*PSD d = -1 while d <335: d = d + 1 y = fpsd[d] y1 = y1 + [y] m = np.mean(y1) m1 = m1 + [m] print m1 -------------------------------------------------------------------------------- My purpose is make a list of [mean(fpsd[0]), mean(fpsd[1]), mean(fpsd[2]).. mean(fpsd[335])]. Each y1 would be the list of fpsd[d]. I check it is working pretty well before second while l...

stop an if loop in a for loop
Hello, I try to find a way to stop an if loop inside of a for loop but keep the for loop going. I tried to use "return" and "break" but they stop the for loop too. Bellow is a simple script to explain what I mean. Using "return", it stops the loop when z = 2 but I would like to find a way to keep the for loop going until z = 3. i = 1; for z = 1:3 i = i+1; if i ==3 return % Stop the if loop else display('Cant do it') end end Thank you for you help Benoit "Benoit " <igneb@iastate.edu> writes: > Hell...

Loop within a loop ???
Hi, I'm having trouble copying table data to new records. I have two tables as follows: *** Specifications (Table) specification_ID (field) LINKED product_ID (field) specification_header (field) ________________________________________ *** Specification_detail (Table) specification_detail_ID (field) specification_detail_text (field) specification_ID (field) LINKED specification_ID in this table is linked to specification_ID in Specifications. ________________________________________ On a form, related by product_ID, 'Specifications' fills a subform, no problem. When you cli...

conditional loops (while loops)
I am using a while loop to check a digital input. I would like to send the value to a true or false box to check another digital input. The problem is that the while loop is running continuously but not giving anything out through the connection. I am looking for something like "if this do that conditional". Is there a way to set this up? Hello! The =93if this, do that conditional=94 tools in LabVIEW are the Select function (All Functions >> Comparison subpalette) and the Case Structure (All Functions >> Structures subpalette), depending on the complexity of what you wa...

Loop-Loop Calculation
Hi &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i have one VI in that i want to do Loop to Loop calculation. In my VI first the inner loop have to execute first . Loop-Loop calc.vi: http://forums.ni.com/attachments/ni/170/302256/1/Loop-Loop calc.vi I think you should explain better what you wean by "loop to loop calculation". What are you trying to accomplish? ...

while loop inside a for loop
Hi, can someone please tell me why "time" (t) is not updated correctly within the while loop? Please run this small code in your machine and you'll know what I'm taking about. What I want is: for t=1 run the "while loop" until iq<=(numberc-1) then t=2 run the "while loop" again until iq<=(numberc-1), and so on. Basically, this code runs through all the nonzero elements of A and attempts to divide them individually into two, once a certain time has passed. Please feel free to ask for clarifications. Many thanks in advance. A=[0 0 0 0 0 0 ...

open-loop to closed-loop Narx NN in Matlab Help
Dear all, In the Matlab NN Toolbox help (2010b), there is a section for dynamic NN using Narx NN. Here the help shows us that after we had successfully train the Narx NN in the open loop manner (aka feedforward NN), we can closed it (using some command) to become closed loop Narx NN (aka recurrent NN). So, I am had some confusions regrading this matter:- 1- It this technique is acceptable? For what i know, to develop a recurrent NN, you have to train the NN closed-loop. Not just by simply closing the loop. 2- So, now since the Narx NN is in closed loop, so what do we call it afterwards: a Feedforward or Recurrent NN? If Recurrent NN, the training happen earlier is in open loop not in closed loop. If feedforward NN, the network now is in closed loop scheme. 3- Training using close-loop Narx is so long. Is there any way to make the training go faster? (expect for reducing the amount of data) Thanks in advance for you help. "Dinie Muhammad" <annursi@gmail.com> wrote in message <k5igvc$399$1@newscl01ah.mathworks.com>... > Dear all, > > In the Matlab NN Toolbox help (2010b), there is a section for dynamic NN using Narx NN. Here the help shows us that after we had successfully train the Narx NN in the open loop manner (aka feedforward NN), we can closed it (using some command) to become closed loop Narx NN (aka recurrent NN). So, I am had some confusions regrading this matter:- > > 1- It this technique is acceptabl...

Nested loops, does it run the inner loop first then the outer loop?
I wrote this simple code for i=1:6 for c=1:6 fprintf('%i\n c:',c); fprintf('%i\n i:',i); end end and got the following output c:1 i:2 c:1 i:3 c:1 i:4 c:1 i:5 c:1 i:6 c:1 i:1 c:2 i:2 c:2 i:3 c:2 i:4 c:2 i:5 c:2 i:6 c:2 i:1 c:3 i:2 c:3 i:3 c:3 i:4 c:3 i:5 c:3 i:6 c:3 i:1 c:4 i:2 c:4 i:3 c:4 i:4 c:4 i:5 c:4 i:6 c:4 i:1 c:5 i:2 c:5 i:3 c:5 i:4 c:5 i:5 c:5 i:6 c:5 i:1 c:6 i:2 c:6 i:3 c:6 i:4 c:6 i:5 c:6 ...

getElementById in a for loop whose target div id is being looped in that for loop.
Hello! Thanks for reading my question first! I have many divs with an numeral id ,for example <div id="999">...</div>, <div id="1000">...</div> and I wish to do something like this, for( var i = startvalue; i<=endvalue; i++){ document.getElementById(i).style.background="yellow;"; } but after the first changing background, it stops and tell me that the document.getElementById(i) has no properties. And I am sure that those div's exist. What's going wrong? Thanks So Much! Nik said the following on 12/15/2006 12:08 AM: > ...

Comparison in a while loop between a 7th loop valuee and 8th loop value
I have a value (voltage input) in a while loop that changes, maybe not every loop, but every 10 or so. Every loop I have to make a comparison between the previous loop voltage, and the voltage I am receiving from the current loop. If it did not change, then I have to do nothing. If it did change, I have to AO the voltage plus a certain increment. I have no idea how I could do this. Help!!! It worked perfectly, thanks! ...

Getting a loop to activate a loop above it
The following code will not work for me: x = 1 while x == 1: print 'hello' x = input('What is x now?: ') while x == 2: print 'hello again' x == input('What is x now?: ') The second loop dose not seem to be able to activate the loop above it.... Proof from my command line: $ python program-that-dose-not-work.py hello What is x now?: 2 hello again What is x now?: 1 hello again What is x now?: So, now I ask you: how do I make it work? Thanks in advance, -- /usr/bin/byte x=1 while not x==3: if x==1: print 'hello' ...

"While" loop not looping
Hi there. Here is a snippet of code that creates binary matrices and checks to see if they have an inverse that is also binary. I use "ismember" to verify that each element in the inverse is either 0 or 1. Unfortunately, the "while" loop exits immedeately. Why? set=[0,1]; a=round(rand(7,5)); inverse=pinv(a); while ismember(inverse,set)~=ones(size(ismember(inverse,set))) a=round(rand(7,5)); inverse=pinv(a); pause(0) end a inverse TIA majb bourassa <bourassa-m@rmc.ca> writes: > Hi there. Here is a snippet of code that c...

parfor loop with nested for loop
Hi all, I'm new to this group, but googling my problem always points here so I thought I'd sign up. I'm running multiple iterations of a time-evolving Monte Carlo simulation in Matlab. Since each iteration is initialized randomly at the first time point, the iterations can safely be run in parallel on a quad core PC. I've previously been doing this by simply running 4 simultaneous Matlab sessions on one machine, but I thought I would save my institution some licenses and automate the process at the same time. The problem is that my code essentially has multiple nested for ...

break out of a while loop from outside the loop
Hello, I have an application where I have some nested while loops. Is it possible to break the innermost loop from a control that is outside of the inner loop? My inner loop is running a scan and read operation on the serial port and is reading data as it somes in. I need this loop to break when the user presses a button located in one of the outer loops so that another section of the vi can execute. Thanks in advance. Greg Create a local variable to outer control and wire it in the inner post loop. When you set the value of outer control, the local variable accessed its value in the in...

nesting for loops in a parfor loop
Hi, I am trying to nest several for loops in a parfor loop. I have even read the documentation and several other queries/replies before posting here. I have a large dataset that I need to iterate over, calculating a property which would result in a prohibitively large array if I sent each answer to a separate element, and doing this on one cpu will take a prohibitively long time. Instead, what I am doing is reducing the array by another property, and then combining the calculated results in bins of this second property (essentially making a histogram). The parfor section of my code looks like this: parfor i=1:box(1); for j=1:box(2); for k=1:box(3); for l=1:box(1); for m=1:box(2); for n=1:box(3); prop(horrendousfunction(i,j,k,l,m,n)) = prop(horrendousfunction(i,j,k,l,m,n)) + data(i,j,k)*data(l,m,n); end end end end end end Trialling this on one cpu over i=j=k=l=m=n=[1:15] works fine and takes a few minutes. The data array is the initial large array, but as written the code will iterate over every element of it many times within each parfor step, and therefore the data transmission I/O overhead shouldn't be too onerous with respect to the overall computation time. (Expected complete running time is ~1 month on 1 cpu, and I have several of these to do) A few other (small, negligible I/O) arrays are also required. hor...

For loop and while loop. which one is faster?
For loop and while loop. which one is faster? I see many articles fighting over it and different people come up with different results. mgcclx@gmail.com wrote: > For loop and while loop. which one is faster? > I see many articles fighting over it and different people come up with > different results. Unless you're designing a compiler, don't worry about that. Worry about the algorithms instead. That said, the only possible difference between a for loop and a while loop is the jump prediction in your architecture's code instruction set. e.g. the processor can suppose t...

A loop within another loop..
Hi. Hopefully you will see the code and see what I'm trying to do, and see the problem. The loop seems messy, but my method to help with eye strain is to match up the do-end's down an imaginary column... ie: array.each # do # |i| puts i # # <-imaginary column # end # ##### So here's the code. ########### def foo(argument1, argument2) #1 user = [2,5] user.each do |bar| output = [] #2 argument1.each do |i| #3 if i.parent.id == bar.id #4 output << i.parent.name end end ...

Nested While loop inside For loop
I have been coding in matlab for a while and I am confused about the below code: It seems like the "For loop" iterator variable "Index" does not update inside the "While loop". Please help me understand! I hate to assume this is some error induced on Matlab's end. ---------- CODE ------------ for Index = 390000:length(Stopxy) fprintf('Index: %d, \n',Index); while (Stopxy_YCoord(Index) < LowToHighThresh) fprintf('Index: %d, Yval: %f \n',Index,Stopxy_YCoord(Index)); Stopxy_YCoord(Index); Index = Index + 1; ...

Converting a nested for loop to a while loop.
I am working on a problem where I need to convert a nested for loop to a while loop. I've got the problem partially solved but I was only able to get the code to initialize the first row of the Array. Where am I going wrong? Here is the initial code that I made for the for loop: A = [3 5 4;-8 -1 33;-17 6 -9]; B = zeros(size(A)) for i = 1:1:size(A,1) for j = 1:1:size(A,2) if(A(i,j) >= 1) B(i,j)=A(i,j)+20 else B(i,j)=log(A(i,j)) end end end Here is what I came up for the while loop: B = zeros(size(A)); i = 0; j = 0; while i < size(A,1) ...

Web resources about - For loop while loop - comp.soft-sys.matlab

Donald Trump Torching Attracts Nearly 3M To CNN Democratic Candidates’ Town Hall
Last night, 2.7 million total viewers watched the Democratic Town Hall live from Columbus, Ohio, on CNN . That included 811K in the news demo. ...

Xbox One Will Support Cross-Platform Multiplayer With PS4, PC
If you like playing online multiplayer games on your Xbox One but hate that you can never play your pal because she’s a PlayStation 4 devotee, ...

UN Security Council Condemns Ivory Coast Attack
UN Security Council condemns Ivory Coast attack that killed 18 people in beach resort town

Microsoft beefs up Skype for Web with calls to landlines and mobile, YouTube embeds
Microsoft is fleshing out the Skype for Web app with some welcome new features that combine the best of the desktop app with the benefits of ...

Muhammad Jamal Amin: American ISIS Fighter Reportedly Captured In Iraq
Muhammad Jamal Amin, an American who left the U.S. and tried to join up with ISIS, has been captured by Kurdish forces as the would-be jihadist ...

‘The Walking Dead’ season 6, episode 13 recap: Is Carol about to go soft on us?
Last week's cliffhanger left me more anxious than ever to see last night's episode of The Walking Dead . In case you don't recall, in the previous ...

Europe and Russia just launched a Mars space mission to sniff out signs of life
A European-Russian spacecraft headed out from our humble little planet to space today, in search for life on Mars.

Putin orders start of Russian forces' withdrawal from Syria
Reuters Putin orders start of Russian forces' withdrawal from Syria Reuters MOSCOW Russian President Vladimir Putin said on Monday he would ...

Official: Engineer Noticed Bend in Rail, Hit Emergency Brakes Before Kansas Derailment
Official: Engineer noticed bend in rail, hit emergency brakes before Kansas derailment

‘Orphan Black’ Season 4 Trailer Teases Delphine’s Fate
The new trailer for “Orphan Black” season four is punctuated by Sarah’s screams and baby talk. The latest video also teases Delphine’s fate, ...

Resources last updated: 3/14/2016 8:33:21 PM