# MATLAB Basics video: Storing data in a matrix from a loop 88

Posted by **Doug Hull**,

I was recently answering a question that came in from a MATLAB user on this blog. In the end, the question was really one where he was doing a calculation and storing the result in scalar Y. When he was done with the loop, he only had the final value of Y but not all of them that he had calculated on the way. The solution to this was to store each value of Y into a vector. This video is meant for new users to show how to do that.

If you would rather download the video, you can get it from the File Exchange.

Also note, that I have been reformatting these videos and tagging them as videos. If you click on videos under categories to the right, you can see all the videos in one place.

Other videos have been gathered here:

http://blogs.mathworks.com/pick/category/video/

Other MATLAB Basics posts have been gathered here:

http://blogs.mathworks.com/pick/category/matlab-basics/

**Category:**- MATLAB Basics,
- Video

## 88 CommentsOldest to Newest

**1**of 88

Hi,

At the end of the video you mentioned that you can do this with matrices by creating a 3D matrix. What would the indices look for that for say a 4×4 matrix?

Y(4,4,i) ?

**2**of 88

Kay,

They would look like this:

>> a = rand(4,4,2)

a(:,:,1) =

0.1524 0.0782 0.0046 0.0844

0.8258 0.4427 0.7749 0.3998

0.5383 0.1067 0.8173 0.2599

0.9961 0.9619 0.8687 0.8001

a(:,:,2) =

0.4314 0.1455 0.5499 0.3510

0.9106 0.1361 0.1450 0.5132

0.1818 0.8693 0.8530 0.4018

0.2638 0.5797 0.6221 0.0760

>> a(1,2,2)

ans =

0.1455

Doug

**3**of 88

First of all, I am resently enjoying learning Matlab skills from here. Thank you very much for your kind instructions.

Today, I have question.

As you can see below I am trying to gather data(all column vectors) from many Excel sheets.

fileName=’a.xls’

range=’A1:A500′

for i=1:39

x=xlsread(fileName, i, range);

x=[x xlsread(fileName, i+1, range)];

end

“But problem is that the size is not same.”

How should I solve this problem?

sincerely from novice.

**4**of 88

Tutorial gave very helpful insight to my problem, but it seems to have generated a new problem in my case.

The values you display are for positive iterations, but say i wanted to do -10:10 and get the values stored at each iteration….

I realize this is not possible with the method used in the tutorial..since the values are stored in a vector and only the elements from +1 on are able to be accessed….

i’ve spent countless hours messing around with it and cant seem to find a solution….if u have any solution to this problem I would really appreciate the help…

**5**of 88

DH Cho,

Use a cell array instead of growing the vector/matrix inside the loop.

fileName = 'a.xls';

range = 'A1:A500';

x = cell(1, 39); % Preallocation

for k = 1:39

x{k} = xlsread(fileName, k, range);

end

The data from the kth sheet will be in x{k} (note the curly braces instead of parentheses.)

JJ Garza,

If you want to run your iterations from -10 to 10 and store all the data, I can think of two easy ways to do so. Method 1 involves transforming your FOR loop counter to use as indices:

x = zeros(1, 21); % Preallocation

for k = -10:10

% since we want to store k = -10 in element 1 of x

% we need to add 11 to k to make it the correct index

x(k+11) = k.^2;

end

Method 2 is to use the FOR loop index not as the actual iterates, but to index into another vector. For example:

y = -10:10;

x2 = zeros(size(y)); % Preallocation

for k = 1:length(y)

x2(k) = y(k).^2;

end

The latter scenario is useful when it would be difficult or impossible to find a way to map the iterations you want to do to the indices where you want to store the result. For instance:

y = [2 3 5 7 11 13 17 19 23];

x = false(size(y));

for k = 1:length(y)

x(k) = isprime(y(k));

end

It would be hard to convert the elements of y into [1, 2, 3, …] to use as indices.

**6**of 88

Hi I am trying to write a for loop for a project and I am having trouble with the output.

Within my for loop I am invoking a function that I created in an mfile. The output of the function from the mfile is a 3×27 matrix. I am trying to save all the outputs from the for loop to create a bigger matrix (33×27) which is all the outputs from going through my for loop 11 times.

code:

for i=1:numj

coef(i)=jeq(i,jcoor,bconnect);

end

coef

I keep getting this message:

In an assignment A(I) = B, the number of elements in B and

I must be the same.

Error in ==> Main at 98

coef(i)=jeq(i,jcoor,bconnect);

Please help. Thank you.

**7**of 88

Joseph,

Here is a similar problem:

———–

out = ones(5,3); %could be 3×27

big = [];

for i = 1: 3 %could be 11

big(:,end+1:end+3) = out

end

———

The key line: big(:,end+1:end+3) = out

I would pronounce this aloud as:

matrix named BIG, all rows and column numbers one bigger than the current number of columns through column numbers three bigger than the current number of columns will be set equal to the matrix named OUT.

This is specifiying a target inside of BIG that is the same size as the OUT matrix.

-Doug

**8**of 88

Hi there, i guess my problem will be easily solved for you, but i unfortunately have no idea how to do it.

Lets say i have a matrix like this:

Data= [1 1 1 0 1 1

1 1 0 0 1 1

1 1 1 1 1 1

1 1 0 1 1 1

0 1 1 1 1 1

1 1 1 1 1 1 ];

What i want to do, is to get the “coordinates (column & row number)” of each of the 0 values. What i have done this far:

[rows cols]=size(Data);

for i=1:rows;

for j=1:cols;

if Data2(i,j) ~= 1

a=[j;i]’

end

end

end

Which gives the correct results, but for each 0 separately. I would need to get them into a matrix, so that i can work with them later.

I would really appretiate your help.

**9**of 88

Pete, try this

[r,c] = ind2sub(size(Data),find(Data(:)==0));

a2 = [c r]

For the same order swap your “i” and “j” FOR loops.

**10**of 88

Thank you Bob, finaly I managed to solve it too, but like this:

%%%%%%%%%%%%%%%%%%%%%%%

k=0;

for i=1:rows;

for j=1:cols;

if Data2(i,j) ~= 1

k=k+1;

a(k,1)=i;

a(k,2)=j;

end

end

end

a

%%%%%%%%%%%%%%%%%%%%

but your way is much more neat, of course.

So ill use your code. :)

thank you.

**11**of 88

Hi Doug,

I tried this code the first time and it does not give me the same results as yours.

for i=1:10

y(i)=i+rand

end

I get the following 10 times:

y = 1.6221 2.1818 3.2638 4.1455 5.1361

6.8693 7.5797 8.5499 9.1450 10.8530

Do you know what’s wrong?

Thanks for your help,

Adrew

**12**of 88

Adrew,

Is that all the code that you are running? I find that hard to understand. I think you may be setting the random seed in your code somewhere. By setting the seed every time you run your code, you will get the same string of pseudo-random numbers.

Doug

**13**of 88

Hi, is there a possible way to store all the numbers into a matrix so it can be used later?

For example, heres my code:

function[] = mfile1(x)

for x=1:10

f(x) = x*3

g(x) = 1 – x*5

end

end

Is there a way to store all the numbers of f(x) and g(x) in a 10×2 matrix for later use, with the first column for values of f(x) and second column for g(x)?

Thank you much help is appreciated

**14**of 88

@Justin,

If you want to store into a matrix rather than a vector, it would be like this:

f(x,1) = x*3

f(x,2) = a – x*5

Enjoy,

Doug

**15**of 88

Thank you Pete …your logic worked for my requirement too..:)

**16**of 88

i am trying to create function that a while loop that prompts the user for a number. if the number is 0 or more, the value is stored in a vector and the user is prompted to enter another number and so on but if the number is negative, the function stops and returns the vector of the previously stored numbers.

this is my code but i know i am doing something wrong in the section where i store the value in a vector and when displaying this vector.

% x is input data value

function [] = whileInput()

x = input(‘Please enter a value: ‘);

while x >= 0

% store value in vector

vector(x) = 1:length(x);

% ask for new value

x = input(‘Please enter your next value: ‘);

end

if x < 0

disp(vector);

else

end

please help. thank you

**17**of 88

vec = []; while 1 val = input('Next value (negative to quit): '); if val >= 0 vec = [vec val]; else break end end

Enjoy,

Doug

**18**of 88

Normally in a loop I’d preallocate the vector into which I’m going to insert data; however, in this case the limiting factor on the speed of the loop is not going to be reallocating the memory for the growing vector but waiting for the user to enter the value so it’s not as big a concern. I would do things slightly differently from Doug’s answer, to avoid the need for the infinite WHILE loop and the BREAK:

val = Inf; vec = []; while val >= 0 val = input('Next value (negative number to quit): '); if val >= 0 vec = [vec val]; end end

or, slightly sneakier:

val = Inf; vec = []; while val >= 0 val = input('Next value (negative number to quit): '); vec = [vec val]; end vec(end) = []; % Delete the negative value at the end of vec

I find it easier to read the code if condition is in the WHILE statement rather than somewhere inside the loop, but that’s just my personal preference.

**19**of 88

Steve,

I can see your point. I think this comes down to “religious issues” I started with something like yours, but I did not like the repeated “val >= 0” statement. I can see that my code obscures the exit condition though.

Thanks for contributing!

Doug

**20**of 88

Hi, I think my problem is simple but its been bugging me. Basically I want to save each step in the loop as a single column vector. Inside the loop is a matrix times a column vector which should result in a colunm vector. In the end I will build a matrix from my collection of vectors i get from the loop. How can I get the loop to save each iteration as a column vector. thanks alot

I’m getting this error message below

??? In an assignment A(I) = B, the number of elements in B and I must be the same.

**21**of 88

@michael,

Without your code, I can not debug this. Please post the shortest version of your code that shows the behavior.

Dou

**22**of 88

Dear Doug

I have a question in your code ‘October 9th, 2009 at 13:53’

vec = [];

vec = [vec val];

I don’t know the meaning of these statements.

I just started the matlab.

So, i don’t know well about matlab.

Could you tell me the meaning?

**23**of 88

@Leo,

Here is the “English version” of that code.

“vec = []” makes an empty variable named ‘vec’.

“vec = [vec val]” makes the variable ‘vec’ equal to the variable ‘vec’ and variable ‘val’ in a row. (This would fail if ‘vec’ was not already defined, thus the above line.) This was done in a loop, so the empty ‘vec’ is there for the first iteration really.

-Doug

**24**of 88

how to store 10 or more random number in a loop a loop

for i = 1:n

mean(i) = input(‘enter the mean value of distribution = ‘)

std(i) = input(‘enter the std value of distribution = ‘)

p(j) = mean(i) + std(i)*randn(100,1);

end

how to make it work becoz there is string mismatch. Please tell me

**25**of 88

@Ashok

First, please do not use variable names that are MATLAB commands (std and mean).

Second, p(j) should be p(i)

Third, look at this line of code:

p(j) = mean(i) + std(i)*randn(100,1);

This says

The jth element of the matrix p should be the sum of a scalar(mean(i)) and a vector(std(i)*randn(100,1)).

This does not make sense to put a vector into the element of a matrix.

Fourth, usually asking for user input like that is slow, and causes trouble since people can type anything.

Enjoy,

Doug

**26**of 88

Hey Doug,

I have a column vector of positive integers and I am trying to create a for loop that will run through each element and create a matrix of zeros with dimensions 210xthe given element at that point in the loop, and then save each of these matrix so that if I have, say, 10 elements in my column vector I will finish with 10 matricies composed of zeros all with 210 rows and a varying number of columns.

I expect it’s quite a simple piece of code I need, do you think you could help me?

Cheers,

Dan

**27**of 88

Dan,

There are many steps in this. What are you having problems with?

1.) Looping through all the elements of a column vector

2.) Getting a value from a vector based on a looping index

3.) Making a matrix of zeros of a given size

4.) Saving a matrix as a file

5.) Saving a series of matrices as a series of files.

6.) Generating unique names for the above files?

What have you tried?

Doug

**28**of 88

Hi Doug, thanks for getting back to me. I have tried looping through the task like so:

>> for j=(1:10)

for i=extra_white_pix_left(1:end)

white_area_left(j)=zeros(210,i);

end

end

this is the error message I get:

??? In an assignment A(I) = B, the number of elements in B and I must be the same.

extra_white_pix_left is a 10 element long column vector, I was hoping to get 10 matrices, each with 210 rows and the ith one having the same number of columns as the ith element in extra_white_pix_left.

**29**of 88

so basically i would have a matrix for white_area_left(1), white_area_left(2), white_area_left(3),… and white_area_left(10).

Cheers,

Dan

**30**of 88

@Dan,

You are attempting to put a matrix (zeros(210,i)) into a single element of a matrix (white_area_left(j)). This can not work.

You might want to try a cell array (white_area_left{j}).

-Doug

**31**of 88

Thanks for that Doug, but the loop still only accepts scalar values, eg. it will only accept i taking the value of one element in the column vector extra_white_pix_left. And what it creates is a cell array where, if i were to be set to 2 for example, each cell states ‘[210×2 double]’ but won’t construct that matrix. How do I get the loop to accept i as a vector and to make a cell array where if each value is called up on it will construct the matrix of the dimensions stated in its cell?

Cheers,

Dan

**32**of 88

Doug, just figured out one of the problems, but can’t get around the fact that the loop will only take scalars and not a vector. Think you could help with that?

Cheers,

Dan

**33**of 88

Doug, I have actually figured this problem out as well. My general problem is how to save the various matrices of zeros that my loop constructs along the way, so that I don’t end up with just one matrix at the end with its dimensions being 210xthe last element in my vector column.

**34**of 88

@Dan,

Use the same command and generate a unique filename for each time through the loop. Do you know how to do this?

Doug

**35**of 88

No I don’t, could you tell me?

Cheers

Dan

**36**of 88

for i = 1:3 fileName = ['File' num2str(i)] save(fileName) end

**37**of 88

what if i is a matrix?

**38**of 88

@Dan,

If i is already a variable (a matrix) use a different variable name for the loop.

Doug

**39**of 88

I mean, how do I carry out the same operation on a matrix, as oppose to the scalar values i takes in your example?

**40**of 88

@dan

I do not understand.

What would a typical matrix input and corresponding output file name be?

Doug

**41**of 88

Doug,

I am trying to write a code for my fluids class. Basically i need it to plot To and Ma variation along the length x. I have a for loop and its pretty simple, but if i try to make To a function of x, it will not take 0 (which i need since its the inlet of the duct. Here’s the code, any suggestions?

% Case 1: Diameter increases linearly by 20%

% With the following inputs:

g=1.4; %Gamma

Mi=0.35; %Inlet Mach number

Ti=313; %Inlet Temperature

Di=0.06; %Inlet Diameter

Dl=1.5 ; %Duct length

ff=0.003; %Friction factor

At=164;

Bt=0;

Ad=0.008;

Bd=0;

Ai=0.0028; %Inlet Area

Pe=0.1885; %Inlet Perimeter

% In order to iterate

for x = (0:0.75:1.5)

D = Di+(Ad*x)+(Bd*x^2)

To(x) = 320.66+164*x

dA = (Ad/2+Bd*x)*pi()*D

dTo = At+2*Bt*x

A = pi()*D^2/4

G=(-2/A)*(dA)+(g*Mi^2+1)*dTo/To+g*Mi^2*ff*Pe/A

sqdM=(Mi^2*(1+0.2*Mi^2/2)/(1-Mi^2))*G*0.015

Ma = sqrt(Mi^2+sqdM)

Mi=Ma

end

**42**of 88

@Mini

>>To(x) = 320.66+164*x

This line here is read as:

Assign to vector To, element x, the value of 320 plus the product of 164 and x. x will take on the values of 0, 0.75 and 1.5. So, it makes no sense to have the ‘zeroth’ element of x.

Maybe if you want to store all of these values you should have an index like this

iii = 0; for x = ... iii = iii + 1 ... To(iii) = ... end

This should do what you want.

Doug

**43**of 88

I enjoyed the video and it helped greatly. I’m wondering: how do I get around not being able to use zero in the for loop? My loop works fine when 1 is the lower bound, but not when I change to zero, saying “??? Attempted to access pois(0); index must be a positive integer or logical.”

Much thanks.

**44**of 88

@David,

Just add one to the loop index? Or just count from one instead of zero. MATLAB is ones based instead of zeros based.

Doug

**45**of 88

Hi Doug,

I am new to Matlab, so please bear with me, I like the solution that you’ve given so far. What I am trying to do is to pull certain ranges of data out of a large matrix(6 x ~ 140 000).Once I’ve isolated the ranges I want, I take the mean and then plot them. More specifically, I am averaging hourly wind data. I can isolate the year and month that I want, and take the mean of the month quite easily, what I am unable to do is to automate the process so that each years worth of monthly means is made into its own vector that I can easily plot.

My code looks a little like:

for q=1994:2009; for a=1:length(d); aa=find((output(1,:)==q)&(output(2,:)==1));

Where output 1 and output 2 are just my year and month rows and I run 12 versions of the second for loop (one for each month).

The final result of this is that I get the 2009 means and can plot them easily, but what I want is all of the means in between as well.

I am afraid that I haven’t been very clear here, but I would appreciate any help I can get at this point.

**46**of 88

@kyla,

Please contact me directly with a more detailed question and with code.

You should not need to make that for loop 12 times, just have a for loop around it to change the month number.

Doug

**47**of 88

Hi,

I am constructing a code that will analyze data from an arbitrary file whose contents are three columns. The code runs without any problems, but to save me from copying and formatting the outputs I want to save the outputs into another file directly. There is a value for a Chi-Squared test run by the code, as well as three other arbitrary parameters. I got the code working for outputting a column vector of the Chi-Squared text results for each ‘i’ value in the for loop, but I want to include the other parameters for each i value. Here is my code:

clear all load etching_june14_curr_50m.txt data=etching_june14_curr_50m; start=1; limit=length(data); r=floor(log10(limit)); dp=round(logspace(0.1,r,1)); dp=[0,dp]; for i=1:length(dp) finish=round(limit-dp(i)); time=data(start:finish,1); R=data(start:finish,3); V=data(start:finish,2); model=@(p,time) real(p(1)+p(2)*(p(3)-time).^-1); p=[0.1,0,1.01*time(end)]; [fit.params,fit.dParams,fit.gof,fit.stddev] = ... fitChiSquare(time,R,model,p,1,0.001); para=fit.params; chisq(i)=fit.gof.chi2/(length(time)-3); info=[chisq']; save into_etching_june14_curr_50m.txt info -ASCII end plot(dp,chisq);

**48**of 88

@Tibbals,

What is the question?

Doug

**49**of 88

Hello,

I have a matrix of data that is 3×1621800. It represents a matrix of theta, phi, and gain. Theta has a resoultion of 0.2 from 0-360, phi has a resolution of 0.1 from 0-90. I would like to decrese the resolution (size of the matrix) so that Theta has a resolution of 1 degree from 0-360, and Phi has a resolution of 1 degree from 1-90. I am a horrible MATLAB guy, but I thinking I could use a nested for loop.

something like

for k=1:(360*(1/0.))

for l=1:(90*(1/0.1))

new_DATA(k,l,:)=DATA(k*10,l*10,:)

end;

end;

I hope you can help me out with this one. Thanks!!

**50**of 88

@marvin,

a = [0 0.1 0.2 0.3 0.4 0.5 0.6;0 1 2 3 4 5 6]

b = a(:,1:2:end)

%b is matrix a (all rows, columns starting at 1 count by two until the end)

Enjoy,

Doug

**51**of 88

I have a quick question. I have a 64×64 matrix and a for loop running through creating 10 of these matrices. I have named the end matrix Mobj, but as in the example above I would like to store each individual matrix before it gets overwritten in the next loop iteration. Below is part of the code.

for a= 1:10 m = rand ; n = rand ; Mobj = dct2mat(m,n,xres,yres) ; Mobj = Mobj - min(min(Mobj)) ; Mobj = Mobj/max(max(Mobj)) ; roff = zeros(xres, yres) ; for i = 1:xres for j = 1:yres roff(i,j) =cos((pi/2)*sqrt((i-(xres+1)/2)^2 + (j-(yres+1)/2)^2)/... (sqrt( ((xres-1)/2)^2 + ((yres-1)/2)^2 ))).^4 ; end end Mobj = Mobj.*roff ; end

I realize that the code above will not store anything with exception to the last iteration, but this where I am stuck at how to store each indvidual Mobj. Also xres and yres are constants that do not change and dct2mat is a function that is implemented.

**52**of 88

@Josh,

Why would you want 64×64 intermediate matrices of size 64? Since each iteration you are only adding one value, these would be quite boring and just a pain to store. That is 16 million elements in this matrix.

If you really, really need to do this, you could have a three dimensional matrix, where the third dimension was the evolving matrix.

Doug

**53**of 88

I am attempting to create random images (Matrices) via a discrete cosine transform. Then I need each one of these images to be stored independently. In the big picture I am manipulating the image so as to implement an evolutionary algorithm or neural network on the manipulated object to try to get the original image back. I may not have explained this particularly well. Please let me know if this is the case. Also thank you for your reply.

**54**of 88

@Josh,

It would be much more memory efficient, and I suspect easier to store only the final matrix and zero out all the appropriate values when you pull out a matrix from an earlier iteration. The non-zero values are added in a very simple pattern, so a quick subfunction would be easy to construct that would give you these intermediate values without the storage overhead.

Doug

**55**of 88

Hi. I have one question.

I have this code:

n=input('insert value: '); for i=1:1:n E(i)=1+i; x(i)=10+E(i) end

say I put n=4, I will get the following:

x = 12 13 14 15

which was repeated 4 times.

My question is: How do I get x to be the sum of 10+(i=1)+(i=2)+(i=3)+(i=4)? Meaning I would like my answer to be (for n=4) x=22.

Thank you.

**56**of 88

total_bandwidth = 20

for t = 1:1:10 %for 10 periods

contribution = rand(1,4) * total_bandwidth

end

For each time of the loop i’m getting a (1,4) matrix. What should i do if need to form a matrix of the entrire observation for the entire 10 periods.

Also i’m running the simulation for 10 times(which means for every simulation run, i will have 10 periods), how do i

calculate the mean contribution for the entire 10 simulation runs and plot the value.

**57**of 88

total_bandwidth = 20 for t = 1:1:10 %for 10 periods contribution(t,:) = rand(1,4) * total_bandwidth end

**58**of 88

Hi I am trying to write a code for the famous Fibonacci sequence and can’t for the life of me figure out how to out put the information in an array/matrix/vector. If i don’t define a vector /array of some sort, i get all the answers as it repeats but using the same defined names of course since it is looping. what method or how would you rewrite this script in order to output my desired vector/matrix.

clc,clear %Shawn Hansen %Fibonacci sequence % %This program calculats out a user specified fibonacci sequence. A = input('Enter the number at which you want to start the fibonacci sequence: '); B = input('Now enter the second number in the sequence: '); Z = input('Let me know at what amount of numbers you wish for me to stop counting: '); fprintf('Calculating, Please Wait... \n') %displays that during the counting process count=0 ; %Initialize counter to zero C = A; D = B; for k=1:Z; count = C + D; count2 = count + D; C = count2; D = count2 + count; end array = [A,B,count,count2]

out put is correct as long as i do it untill Z = 1, otherwise (and this is obvious since my current vector doesn’t grow with z) i get what ever the last set of count, count2 were/was.

thanks for any help

Shawn

**59**of 88

@Shawn

Watch the video again, but the short answer is you will need some code in there like this

seq(k) = D;

Doug

**60**of 88

I need some help. I am trying to take a set of data points and take a value off of each end depending on the size of the incoming matrix. I want to run a loop until the smallest matrix has three points and want to find the radius of curvature of each sets of data. I have been able to write the code but my equation is not explicitly dependent upon the loop variable. How can I take into account this?

for k = (((g(:,1)-1)/2)+2):1:(g(1,1)-1);

%Now Fitting the Circle using fitcircle.m

% Find the linear least squares fit

[zl, rl] = fitcircle(x(1:2,((g(:,1)+1)-k:k)), ‘linear’);

% Find the best geometric fit

[z, r] = fitcircle(x(1:2,((g(:,1)+1)-k:k)));

Rc=[r(1,1),rl(1,1)]

end

where g is the size of the incoming matrix with certain number of rows and columns. Rc outputs the values I want but I want to accumulate them as the loop continues. Hope you can help. Thanks in advance.

**61**of 88

I can’t see from the video how to store two values. I am using this loop:

x=0 for i=1:10 f=sin(3*x)+cos(x)+tanh(x^2); x=x+0.32 end

I need to store the x value and the f value together before I increase the x value.

Can anyone suggest how I can do this?

**62**of 88

@Susie,

http://www.mathworks.com/matlabcentral/answers/

Is the best place for this kind of question.

**63**of 88

This is my script:

AA=randn(2,3,6);

X =[1,2,3,4,5,6]

L = X’;

Cp=zeros(size(AA,1),size(AA,2));

for i=1:size(AA,1) ;

for j=1:size(AA,2) ;

Y=squeeze(AA(i,j,:))

end;

end;

I would like to store Y values from the loop.

Thank you soo much

**64**of 88

@Ruben,

This is just like the example in the video.

Doug

**65**of 88

Hello and thank you for the quick answer.

I obtained this error:

In an assignment A(I) = B, the number of elements in B and

I must be the same.

Error in ==> Error at 6

Y(i)=squeeze(AA(i,j,:));

Maybe it is because in my case the values generated for the loop are vectors?

**66**of 88

@Ruben,

Yes, that is why.

If they are vectors of the same length, you can save them as the rows (or columns of a growing matrix. You could also stuff them into a cell array.

**67**of 88

Hi,

I am trying to run a function, but it is not allowing me to store the values in a matrix.

Here is the code:

h=(b-a)/n

for z=a:h:b

i(z)=funct(z)

end

a and b are inputs, and funct is also a function specified by the user (to find integral of).

It generates the values when I do not try to store the values in an array, however, when I do try the array I get an error message of “??? Attempted to access i(0); index must be a positive integer or logical.

Error in ==> ictrap at 8

i(z)=funct(z);”

What could be wrong here?

**68**of 88

@Mark

MATLAB is ones based. You can not have an index of 0. Just add 1 to z in the index.

Doug

**69**of 88

Doug,

I am not exactly sure what you are saying. Are you saying that the code should read this:

h=(b-a)/n

for z=a:h:b

i(z+1)=funct(z)

end

That worked to come up with the first value, but after the second it did not work. It was also trying to find the function of 1+ the value that the function was to be found of.

Thanks for the help.

**70**of 88

I have a forloop that I am running, and I am trying to create a vector from it. The problem is that the forloop does not have integer values. I am running it from a value such as 0.556 to 4 with 0.01 intervals. (I’m currently running it at 0.3 intervals to save time)

Those values in the forloop cannot be changed since the code is written to use the values such as 0.556, etc.

Do you have any suggestions on how to tackle this problem?

here’s an example:

for sliderValue=0.556:0.3:4

moneyloss=y3+y5+y9;

end

if I try:

for sliderValue=0.556:0.3:4

moneyloss(sliderValue)=y3+y5+y9;

end

matlab has an indexing problem

Any help is greatly appreciated.

Christopher

**71**of 88

@Christopher

Indices must be integers. You are feeding it numbers like 0.556

Doug

**72**of 88

Hi,

I tried the exact same code as shown in the video, but rather than getting a vector that increases by one value each time, each vector has 10 values in it. Why is this the case for me?

for i = 1:10 y(i) = i + rand end

Any ideas / help would be greatly appreciated!

**73**of 88

sorry, this is my output:

y = Columns 1 through 3 1.655740699156587 2.970592781760616 3.957166948242946 Columns 4 through 6 4.485375648722841 5.800280468888801 6.141886338627216 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.957166948242946 Columns 4 through 6 4.485375648722841 5.800280468888801 6.141886338627216 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.485375648722841 5.800280468888801 6.141886338627216 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.800280468888801 6.141886338627216 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.141886338627216 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.757740130578333 Columns 7 through 9 7.421761282626275 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.757740130578333 Columns 7 through 9 7.743132468124916 8.915735525189067 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.757740130578333 Columns 7 through 9 7.743132468124916 8.392227019534168 9.792207329559554 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.757740130578333 Columns 7 through 9 7.743132468124916 8.392227019534168 9.655477890177556 Column 10 10.959492426392902 y = Columns 1 through 3 1.655740699156587 2.035711678574190 3.849129305868777 Columns 4 through 6 4.933993247757551 5.678735154857773 6.757740130578333 Columns 7 through 9 7.743132468124916 8.392227019534168 9.655477890177556 Column 10 10.171186687811561

**74**of 88

Thank you SO much for posting this; this has helped me GREATLY writing my script.

**75**of 88

Thank you so much……I just passed my test because of your help from the video!! Please I insist you to put more of these videos and make a compilation.

**76**of 88

Hi,

I’ve created a function with one input and three output.

Example:

function [out1 out2 out3] = F(input)

Then I’ve used the output in some file.m, which passes them as single values. My problem is that; I need to save all the output for each iteration number “say (i=1:100)” as a vector.

How do I do that; Note that when I’ve used global out1…out3 it keeps over write the values, and saved only the last value at the end of the loop.

Thanks

**77**of 88

hi….if i am using for loop inside another for loop how am i going to store the values in a vector??

**78**of 88

hi….if i am using “for loop” inside another “for loop” how am i going to store the values in a vector??

**79**of 88

@ Majj

Probably store in a matrix:

for r = 1: 10; for c = 1: 10; m(r,c) = rand; end end

**80**of 88

Very helpful information .. thanks very much

**81**of 88

Hey Doug, I really liked the video and the job ur doing here. May I as well bring forward my query, as another novice in Matlab.

I need to store output of a function:

[x, y]=myfunc(imagefile), from a no. of (144) image pairs (each pair with members 1 & 2) from a directory.

they are .tif images; member1 filenames are ‘*0(.tif)’ and member2 filenames are as ‘*1.tif’. I need the store all outputs of member1 files in matrix(/array) A, and the others in B (say).

Also need to know if this’s better off as a subfunction of myfunc,or as a script in the same directory. Please help.Thanks a lot.

**82**of 88

How can I use this code to assign the parameters of membershi function ‘mf’ of 1 and 2 to vector VParam using for loop. I tried but it gives only one mf parameters.

VParam=getfis(x,’input’,1,’mf’,1,’params’);

**83**of 88

This is exactly what I wanted to see! Thanks a lot

**84**of 88

I have a similar problem of overwriting in sys function where the output of the .m file is to be carried over to simulink. Can I use this same method for that problem?

**85**of 88

Hi, Thanks for the tutorial.

However, when I tried the matrix after loop method which you showed, it didn’t work as expected.

What do you think is wrong with the following code?

Thanks in advance.

for i=1:22

syms x

solve (log(x(i))-(A(i)-B(i))/0.67)

end

**86**of 88

Hello, i’m rookie so please be gentle. :)

I got a problem in handling matrices with for loop command.

This is the code i try to do.

Q(1)=zeros(5,1);

Q(2)=zeros(5,1);

for i=3:1751

P(i)=-M1*XXX*data_ug(i)

Phat(i)=P(i)-(a*Q(i-1))-(b*Q(i))

Q(i+1)=(Phat(i)\Khat)’

end

Q

actually i want to solve Q, all are matrices instead of vector. Q(i) are 5*1 matrices; P(i), Phat(i), and Khat are 5*5 matrices.

i always get message

In an assignment A(I) = B, the number of elements in B and I must be the same.

i try to assemble Q in a 5*1751 matrix so i can return the value of the 5th row only (and then plot it in a graph).

i think this code i wrote is only suitable for vector instead of matrix. could you please help me with it?

thanks a lot.

**87**of 88

oh i’m sorry, P(i), Phat(i) are 5*1 column matrices too. data_ug(i) are vectors :)

**88**of 88

Hey, can somebody tell my why the following is not working:

function[x]=importbmp

for k=1:100

x(k)=imread(strcat(‘image name’, num2str(k), ‘.bmp’))

end

It works if I replace x(k) by x, but then I only get only the result of the 100th run as my output. I of course want to import all images, not only the 100th.

Thanks already.

## Recent Comments