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.
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) ?
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…
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.
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.
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.
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.
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.
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)?
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
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.
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.
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.
“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.
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
Leave a Reply
About
Bob, Brett & Jiro share their favorite user-contributed submissions from the File Exchange.
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) ?
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
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.
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…
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.
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.
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
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.
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.
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.
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
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
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
@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
Thank you Pete …your logic worked for my requirement too..:)
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
vec = []; while 1 val = input('Next value (negative to quit): '); if val >= 0 vec = [vec val]; else break end endEnjoy,
Doug
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 endor, 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 vecI 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.
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
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.
@michael,
Without your code, I can not debug this. Please post the shortest version of your code that shows the behavior.
Dou
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?
@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
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