matlab,loops,for-loop,while-loop,do-while , Matlab: Looping through an array

Question:

Tag: matlab,loops,for-loop,while-loop,do-while

This is my one dimensional array `A`. containing 10 numbers

``````A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
-2.57400000000000 -4.52700000000000 9.63300000000000 ...
4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];
``````

I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8

1. `(a(1)+a(2))/2` - value stored in one block of a matrix say m= zeros(10)
2. then `(a(1)+a(2)+a(3)+a(4))/4` ------ mean-----
3. then `(a(1)+a(2)..... a(8))/8`

then shift index;

1. `(a(2)+a(3))/2;` - mean
2. `(a(2)+a(3)+a(4)+a(5))/4`
3. `(a(2)+a(3)...a(9))/8`

SO basically 2^n length interval

You could do this using `conv` without loops

``````avg_2 = mean([A(1:end-1);A(2:end)])

avg_4 = conv(A,ones(1,4)/4,'valid')

avg_8 = conv(A,ones(1,8)/8,'valid')
``````

Output for the sample Input:

``````avg_2 =
0.8445    5.9715   -0.6205   -3.5505    2.5530    6.9475   10.6100   12.5635    6.4600

avg_4 =
0.1120    1.2105    0.9662    1.6985    6.5815    9.7555    8.5350

avg_8 =
3.3467    5.4830    4.7506
``````

Finding Standard Deviation for an example (`std_4`)

``````%// each 1x4 sliding sub-matrix is made a column
%// for eg:- if A is 1x6 you would get 1-2-3-4, 2-3-4-5, 3-4-5-6 each as a column
%// ending with 3 columns. for 1x10 matrix, you would get 7 columns
reshaped_4 = im2col(A,[1 4],'sliding');    %// change 4 to 2 or 8 for other examples

%// calculating the mean of every column
mean_4 = mean(reshaped_4);

%// Subtract each value of the column with the mean value of corresponding column
out1 = bsxfun(@minus,reshaped_4,mean_4);

%// finally element-wise squaring, mean of each column
%// and then element-wise sqrt to get the output.
std_4 = sqrt(mean(out1.^2))
``````

Output for the sample Input:

``````std_4 =

7.0801    5.8225    5.4304    5.6245    7.8384    4.5985    5.0906
``````

Full code for OP

``````clc;
clear;
close all;

A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
-2.57400000000000 -4.52700000000000 9.63300000000000 ...
4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];

reshaped_2 = im2col(A,[1 2],'sliding'); %// Length Two
mean_2 = mean(reshaped_2);
out1 = bsxfun(@minus,reshaped_2,mean_2);
std_2 = sqrt(mean(out1.^2))
reshaped_4 = im2col(A,[1 4],'sliding'); %// Four
mean_4 = mean(reshaped_4);
out1 = bsxfun(@minus,reshaped_4,mean_4);
std_4 = sqrt(mean(out1.^2))
reshaped_8 = im2col(A,[1 8],'sliding'); %// Eight
mean_8 = mean(reshaped_8);
out1 = bsxfun(@minus,reshaped_8,mean_8);
std_8 = sqrt(mean(out1.^2))
``````

Related:

How can I iterate through nested HTML lists without returning the “youngest” children?

javascript,jquery,html,list,loops
Fiddle: https://jsfiddle.net/zayjeLrk/12/ I want to iterate through an HTML nested list that is 3-layers deep. <ul> <li>animals <ul> <li>birds <ul> <li>crow</li> <li>parrot</li> </ul> </li> <li>reptiles</li> </ul> </li> <li>plants</li> <li>bugs</li> </ul> I want it to iterate through the list so that it returns the elements in this order (note, this isn't...

How to match words in 2 list against another string of words without sub-string matching in Python?

I have 2 lists with keywords in them: slangNames = [Vikes, Demmies, D, MS Contin] riskNames = [enough, pop, final, stress, trade] i also have a dictionary called overallDict, that contains tweets. The key value pairs are {ID: Tweet text) For eg: {1:"Vikes is not enough for me", 2:"Demmies is...

How to access variables in the properties block of a Matlab System Object?

I am working on a simple System Object in Matlab/Simulink. It looks like this : classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates % correlateHeader % % This template includes the minimum set of functions required % to define a System object with discrete state. properties Header %nrOfBitsInPreviousStep=0; s=100; d=zeros(1,s); end properties...

Giving a string variable as a filename in matlab

string,matlab,filenames
I am using the below mentioned code to get the file names of images according to their id's from images_1 text file as strings and use them to read the images from their directory image_count=1; for image_count=1:6 file=fopen('D:\Academics\New folder\CUB_200_2011\images_1.txt','r'); C = textscan(file, '%s'); original_image=imread('D:\Academics\New folder\CUB_200_2011\images\%s','C{1}{2*(image_count)}'); imshow(original_image) end I am able...

java,file,loops,path
This question already has an answer here: java.lang.IllegalStateException: Iterator already obtained 1 answer so I wrote a little Java program to test a little stack language I made vie various test file, but for some reason it won't work. Here is the code: import org.apache.commons.io.FilenameUtils; import java.io.IOException; import java.nio.file.*;...

echo both users

php,mysql,sql,database,loops
The code at the bottom of this post currently echoes: Name: Spongebob Squarepants Description: I live in a pineapple under the sea. Role: editor But there are two users in "wp_usermeta". It's only echoing one. The result needs to look like this: Name: wp_dev_05 Description: My name is Chris Topher!...

Animate through multiple 2D Matlab plots

matlab,plot
I have multiple 2D line plots in Matlab (they represent some wave moving through space). Each plot represents the wave at some time t. I want to animate through these plots (i.e. show the first plot for a fraction of a second, then show the next one, and the next,...

Why black surf from this Matlab command?

matlab,time-frequency
Code tfr = abs ( tfr ); [row_size, column_size] = size(tfr); tfr = tfr(1:round(row_size/2), 1:row_size); surf(tfr); view(2); I get in R2014b of OSX 10.10.3 Yosemite but rotating around shows that the cells should not be black Why is the output black? I wonder if this is a hardware problem or...

function wait to execute

matlab,events,delay
In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only...

Create string without repeating the same element jn the string (Matlab)

string,matlab
I have a string "FDFACCFFFBDCGGHBBCFGE" . Could anyone help me to generate a new string with the same order but no element inside repeated twice. Thanks ! The expected output should be like this : "FDACBGHE"...

Matlab — SVM — All Majority Class Predictions with Same Score and AUC = .50

matlab,svm,auc
I'm having a weird problem in training an SVM with an RBF kernel in Matlab. The issue is that, when doing a grid search, using 10-fold cross-validation, for the C and Sigma values I always get AUC values equal to approximately .50 (varying between .48 and .54 depending) -- I...

performance issues executing list of stored procedures

I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...

Plot multiple functions on one figure

matlab,matlab-figure
I'm struggling to plot multiple functions on one figure. Here is the code that I have: syms t a; a=0.9514; F1=0.5*sqrt(3*t^2); F2=-0.28375*t^2+1.155*a*(t-a)+1; F3=1; E1=diff(F1,t); E2=diff(F2,t); E3=diff(F3,t); I want to plot E1, E2 and E3, each only within a certain range, to make a "composite" line. I've tried plotting with ezplot...

How to normalise polynomial coefficients in a fraction?

matlab,polynomial-math
I have the following code: syms z Gc=1.582*(1-0.3679*z^-1)/(1+.418*z^-1); Ghp=.3679*(z^-1)*(1+.718*z^-1)/((1-z^-1)*(1-.3679*z^-1)); T=(Gc*Ghp)/(1+Gc*Ghp); clipboard('copy', latex(simplifyFraction(T))); Which results in following for T: How can I normalise coefficients? I.e. I want the z2 in denominator and z in numerator to have the coefficient of 1. Is there any function in Matlab to do so?...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar
I'm having problems multiplying specific values within my multidimensional matrix by a scalar. My matrix has the following dimension: size(comDatabe) = 5 10 3 397 10 The third dimension is an x-y-z coordinate frame. Something went wrong and now my y-axis is defined upside down for one subject (#8 out...

How to create series of pandas dataframe by iteration

python,loops,pandas
I want to create df_2008 to df_2014 from an original df by iteration. df has columns names '2008' to '2014' and I want to seperate them into different dfs. I tried for i in range(2008, 2015): 'df_'+str(i)=df[str(i)] Which won't work. I would really appreciate it if anyone could help me....

Methods within my while Loop not working

python,loops
I'm making a simple script that looks to see if my favourite YouTuber Casey Neistat has uploaded a new video. I want the script to loop over and over so see if there is a new video or not. However, whenever I run the program it continually says that there...

How to switch Matlab plot tick labels to scientific form?

matlab,plot
I have a semilogarithmic plot which works so far with semilogx. Now I would like to change the tick labels. Now it says 10^8 10^9 ... 10^13, but I would like to see 1e8, 1e9, ... 1e13 on the x-axis. How can I change that? Cheers Manuel...

Add mouseListener to Labels in Array Loop

java,loops,mouselistener
I want to add mouseListener to all labels in the array. Every label should show an other card of the layout. If I use below code, all labels show card6. What is wrong? sorry this is correct code.. panList = new JPanel(); panList.setBounds(0, 0, 206, 517); panList.setLayout(null); cs.add(panList); CreateCards(); int...

Appending a data frame with for if and else statements or how do put print in dataframe

r,loops,data.frame,append
How do I put what I printed in a dataframe with a for loop and if else statements? Basically, this code: list<-c("10","20","5") for (j in 1:3){ if (list[j] < 8) print("Greater") else print("Less") }) #[1] "Less" #[1] "Less" #[1] "Greater" Or should it be something more like this? f3 <-...

Interface Controls for DoEvent in Excel

excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop
I was building a javascript for loop and I want to compare the value of an array to the next value in the array. If both values are not equal, I want to return true, otherwise I want to return false. In the code below I pass the string "aba",...

How to force my output data in a inputdlg on Matlab be a double?

matlab,typeconverter
I'm currently using a MATLAB to work and I need some help: I need to convert my output data (variable: units) be a double instead of a cell because I must perform a sum: units = inputdlg(question,title); sum = units + i; I've tried this code also but didn't solve...

thicken an object of image to a curve in matlab

matlab,image-processing
I have a labeled matrix containing two objects. How can I thicken an object to a curve? Actually I have the following image: and I want this: Each pixel of the resulting curve is the median of each column. But if you have another idea, it is acceptable, because I...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml
I am learning about looping thorugh arrays - I want to pass the result of an if else statement in the forEach function (inside another function with array as parameter) to HTML using innerHTML (does not have to be innerHTML if you know better methods I do not mind). It...

Calling function and passing arguments multiple times

python,function,loops
I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

Escape out of 2 Javascript loops (or stop script)

javascript,loops
I have a quiz on my site that will submit if the time is up. After the form submits (via jquery), I would like the timer to stop working. I tried putting return: false after the test submits, but that didn't work. html: <span id="time">30:00</span> javascript: var thirtyMinutes = 60...

How to make function in loop run synchronously?

Am working on a chrome plugin, and need to sendMessage from an 'app page' to a 'content script' and then get the return messages, from inside a loop. But since the loop doesn't wait for the sendMessage to return a value before starting on the next iteration, it is screwing...

How to print iterations per second?

python,performance,loops,cmd,progress
I have a small Python script which sends POST requests to a server and gets their response. It iterates 10000 times, and I managed to print the current progress in command prompt using: code=current_requestnumber print('{0}/{1}'.format(str(code),"10000"),end="\r") at the end of each loop. Because this involves interaction with a webserver, I would...

I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

Nested foreach loop in a While loop can make the condition for the while loop go over?

php,loops,foreach,while-loop
Here is a little background on what I am trying to create. I am creating a function called getNextBilling(\$dateStart,\$dateCount = 20) You give it a period length which is the days you want someone to be billed \$test->period = '2,5,15'; it takes a starting date which I have assigned on...

matlab plots as movie with legend

matlab,plot,legend,movie
i have a question regarding legend for movies. This is my code: fig = figure(); for i = 1: 70000 plot(signal1) hold on; plot([i,i],[-5,5]) plot(signal2,'r') hold off; title('\fontsize{14} my data'); legend('signal1','signal2'); axis tight; f(i) = getframe(fig); end The legend shows the same colors for the first two things I plot....

Counter not working after jumps - assembly language

loops,assembly,counter,increment
For some reason, when i switch to mouse input switch back to keyboard input for my program, increasing and decreasing the counter has no effect. It works perfectly in the first loop where we input characters. Here is the program guys, any advice? look at whatspeed jump for reference after...

MATLAB Access Classreg

matlab
So, I want to be able to look at (read: copy) MATLAB's NonLinearModel method of printing the regression results to the screen such as this. Nonlinear regression model: y ~ (alpha1 - alpha2*t^0.5) Estimated Coefficients: Estimate SE tStat pValue alpha1 1.0253 0.0082253 124.66 4.8823e-24 alpha2 0.0061783 0.00073277 8.4314 4.4834e-07 Number...

Php counting with \$i++

php,loops
I have this in a loop: <?php \$i = 1; echo '<div id="'.\$i.'">' . 'Anchor' . '</div>'; echo '<a href="#'.\$i.'">' . 'Link-A ' . '</a>'; echo '<a href="#'.\$i.'">' . 'Link-B ' . '</a>'; \$i++; ?> This works fine if there is only one object. What do i have to do...

How to build a 'for' loop with input\$i in R Shiny

r,loops,for-loop,shiny
In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

Reading all the files in sequence in MATLAB

matlab,image-processing
I am trying to read all the images in the folder in MATLAB using this code flst=dir(str_Expfold); But it shows me output like this. which is not the sequence as i want. Can anyone please tell me how can i read all of them in sequence? for giving downmark, please...

Get next item in array using iterator using flags

javascript,jquery,loops,iterator,iteration
I am trying to obtain the next object in an object of objects (is you get my drift). I'm looking through the a list of songs, and trying to determine the next song to play. I use the flag playing to check if the song is being played, then i...

Comparing two values in the same row and change if needed

php,mysql,loops
Im trying to compare two values in the same record and if \$minvoorraad > \$voorraad , set \$voorraad = \$minvooraad. Database(cropped picture): This is what i have now but it changes all numbers to same <?php session_start(); include 'connect.php'; \$sql = "SELECT Minvoorraad, Voorraad FROM product"; \$query = mysqli_query(\$con, \$sql);...

How to iterate through a table in its exact order?

loops,for-loop,lua,order
If i try to output this table, they are looped through in the false order: local letters = {DIN1="hi", AIN1= "my", AIN2 ="name", DIN2="is"} for name, value in pairs(letters) do print(name,value) end Expected Output: DIN1 hi AIN1 my AIN2 name DIN2 is Output: AIN1 my DIN2 is DIN1 hi AIN2...

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop
For loop with multiple variables in python 2.7. Hello, I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code import requests name =...

Connecting two binary objects in matlab

matlab,image-processing
I have a binary matrix containing several binary objects and I want to bridge between them. Actually I have the following picture: And the result has to be like this: Is there any function or a shortcut way, other than loops, for this problem?...

Interpolation inside a matrix. Matlab

matlab,matrix
I have a matrix looks like: 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4...

Plotting random signal on circle

matlab,plot,signals,circle
I have some random signal (for example sin signal) with the time scale. t=0:0.1:2*pi y=sin(t) plot(t,y) Now I want to draw this signal on this circle. So the time vector actually becomes an envelope of the circle. Envelope of the circle represents "y = 0" in cartesian coordinate system. Here...

Can we add a statement in between MATLAB codes?

matlab
Is it possible to add statements in between the codes. For example: If I have a code like this, r(:,1) = a(:,1) - a(:,2); Then can I write it as, r(:,1) = a(:,1)("this is a constant") - a(:,2)("this is a variable"); ...

xcorr function with impulse response

matlab,filtering,convolution
I'm trying to design a Wiener filter in Matlab for a deconvolution problem but I'm having a lot of problems. I have a gaussian white noise process with a variance of 1.2 and a impulse response which has length two. Its values are g(0) = 5 and g(1) = 4....

Saving images with more than 8 bits per pixel in matlab

image,matlab,image-processing,computer-vision
I need to save a set of pre-processing images in matlab, resulting in grayscale images. The problem is the fact that these pre-processed images have pixel values higher than 255. If I save them with imwrite() as, for instance, .PNG files, does matlab normalize the values to be in [0,255]...

solve symbolic system of equations inside an array

matlab,system,equation
sorry if it already has a answer..i tried other links but it didn't understand i have 2 1*63 array .landa and v. each of their members are syms. and each v member is a function of all landa members.i have already calculated v members and they are all symbolic equations...

what does ellipsis mean in a Matlab function's argument list?

matlab
What is the ellipsis for in this Matlab statement? frame = insertObjectAnnotation(frame, 'rectangle', ... bboxes, labels); ...I could not find in their online doc....

How can i make a jQuery animation loop on infinite, after it finish?

jquery,loops,animation
I have a jQuery animation, i have a flying monkey that has to rotate from left to right and from right to left, is working fine but i have to make the monkey loop. Right now i have improvised, i have made several divs into each other that rotate after...