# Making a matrix in a loop in MATLAB 68

Posted by **Doug Hull**,

A for loop is used to construct a simple matrix with an underlying pattern. Pre-allocation is addressed in the second half of the video.

**Category:**- Format: Video,
- Level: Basic

## 68 CommentsOldest to Newest

Oleg
replied on

I would use:
: **1**of 68b = bsxfun(@plus, a, (0:4).');

dhull
replied on

@Oleg,
Thank you, you are right and I can see the advantage to knowing that technique.
I, however, have a hard time internalizing and visualizing that kind of construction. Mentally, it takes me a little longer to figure out what bsxfun does. For small matrices like this, I prefer ease of understanding to terseness of code.
For this case, there is no appreciable performance difference, so it is a matter of taste.
FWIW, I do not make up these cases, virtually everything on this blog comes from user questions. If someone is asking me how to make that matrix, then that tells me they are not ready for bsxfun! I only bring out the more powerful (but harder to understand) techniques for the *advanced* section of this blog.
Thanks,
Doug : **2**of 68
ravi
replied on

Hi Doug, great and helpful site here!
Here is the beginning of my code;
: **3**of 68r2=1 r1=10 a=[r2:r1]; for r2 = r2:r1 G = r2/3; sigrad2 = G*a^2; endThis is just a simplification of a larger code but for the crux of the matter is, the for loop calculates vectors for sigrad2, but I would like to store each of the results in a matrix - I have watched the video where you build a vector with y = i+rand inside the loop but haven't been able to extend it to my case. I would then like to plot each of those rows in the resultant matrix against a Could you please help me in building that matrix? It seems simple but I can't figure it out Thanks in advance

dhull
replied on

@Ravi
https://blogs.mathworks.com/pick/2007/08/20/matlab-basics-video/ : **4**of 68
ravi
replied on

@dhull
Yeah I mentioned that I saw that video although that only builds a 1x10 vector but I'm not sure how to expand that code to a mxn matrix : **5**of 68
dhull
replied on

@Ravi,
Add a second loop outside that one that counts across the columns.
Doug : **6**of 68
Chris
replied on

I have an array
( -0.2429 -0.4420 -0.4997 -0.3964 -0.1646 0.1209 0.3669 0.4935 0.4606 0.2803 0.0114 -0.2601 -0.4483 -0.4933 -0.3796 -0.1425 0.1420 0.3813 0.4970 0.4520 0.2620 -0.0107 -0.2785 -0.4568 -0.4894 -0.3649 -0.1213 0.1642 0.3986 0.5045 0.4467 0.2452 -0.0330 -0.2973 -0.4642 -0.4821 -0.3461 -0.0984 0.1833 0.4087).
I want to call the first 8 elements and find their average, and the next 8 elements and find their average up till the end and in the process form another array with a reduced 5 elements. e.g (a b c d e)
How do i do this in matlab please? : **7**of 68
doug
replied on

@Chris,
You would need to pull out the subsets. A for loop would probably work well.
for i:1:8:whatever
do something
end
MEAN is the function to get the mean.
then storing it in a vector:
count = 0
for i = ...
count = count+1;
vec(count) = whatever you save
end
-Doug : **8**of 68
Yaacov
replied on

You can use the reshape function to make your array a matrix with 8 columns, then use the mean function to calculate the mean of every row. Finally, transpose (') to make it a row column:
A=reshape(A,[],8);
mA=mean(A,1);
mA=mA';
: **9**of 68
Monica
replied on

How would I create a 3 by 3 matrix where each element is equal to the square of the sum of its row and column numbers? : **10**of 68
Doug
replied on

: **11**of 68```
for r = 1:3;
for c=1:3;
m(r,c) = (r+c)^2;
end;
end;
disp(m)
4 9 16
9 16 25
16 25 36
```

manju
replied on

how to create multidimensional array in a single loop statement?? or how to declare multiple arrays?? : **12**of 68
Pedro
replied on

Sir,
you help me a lot. I have a problem and your loop give me a "light on mind" rs
Thanks a lot !
Good work. : **13**of 68
AMIT
replied on

i have two excel files and i am trying to call them in matlab,my aim is to check the value in 1st excel file and accordingly edit second
f=xlsread('cbtd.xls');%/ this file has to be edited later
g=xlsread('cbam.xls');
now i have use two nestd for loops and check a condition that
if g(i)(j)<80 then
f(i)(j)=0
and that excel file named f should be edited
thanks in advance DOUG : **14**of 68
Ingrid
replied on

@AMIT: Why do you want to use two for loops? Have a look at this example:
A=magic(5);% Or the matrix from your first Excel file
hv=(A<20); %All elements that are smaller than 20
B=magic(5)*20 %Or the matrix from your second excel file
B(hv)=0;%Change the values of your second file to 0 for which the condition of the first file is true
Of course at the end you need to write B back to the Excel file :-). : **15**of 68
AMIT
replied on

thanks ingrid it worked, now i have another problem , i've generated BW image and it has some spots my aim is to calculate area of each spot(white).. : **16**of 68
Ingrid
replied on

@AMIT: Have a look at bwarea. Btw. there is always technical support that you can contact. : **17**of 68
varinder
replied on

function P = legendre(x,n)
P(1) = 1;
P(2) = x;
P(3) = (3*(x^2)- 1)/2;
P =((2.*(n+1)).* x .*(P(n)) - n.*(P(n-1)))./(n+1);
end
test script:
clear legendre;
x = -1;
P = zeros(1,5);
for i = 3:5
P = legendre(x,i);
end
error:
Attempted to access P(4); index out of bounds because numel(P)=3.
Error in legendre (line 7)
P =((2.*(n+1)).* x .*(P(n)) - n.*(P(n-1)))./(n+1);
Error in new_tb (line 6)
P = legendre(x,i); : **18**of 68
madhavi
replied on

hi i need help in finding the average using for loop...
( -0.2429 -0.4420 -0.4997 -0.3964 -0.1646 0.1209 0.3669 0.4935 0.4606 0.2803 0.0114 -0.2601 -0.4483 -0.4933 -0.3796 -0.1425 0.1420 0.3813 0.4970 0.4520 0.2620 -0.0107 -0.2785 -0.4568 -0.4894 -0.3649 -0.1213 0.1642 0.3986 0.5045 0.4467 0.2452 -0.0330 -0.2973 -0.4642 -0.4821 -0.3461 -0.0984 0.1833 0.4087).,in this array of data in first instance it must find average of fist five elements ..2nd time it must find average of (2+3+4+5+6) elements average....third time( 3+4+5+6+7)...like this it must keep on finding average till the end of the array... : **19**of 68
Stuart McGarrity
replied on

Must to use a loop? Have you written loops before? What do you have so far for code? : **20**of 68
subhendu roy
replied on

sir i need to find 25*5 column(total of 125) of a matrix. using for loop. everytime 1st column will be incremented and so on..please help me to find out.the above video shows error like" Subscript indices must either be real positive integers or logicals." : **21**of 68
satyavratan
replied on

sir. i am dividing a 210*210 image in to several 3*3 matrices and performing few operations inside each 3*3. i have created a 3*3 matrix and i have put for loops for row and column operations. i need to operate the same kind of operations for next 3*3 and so on. help me. : **22**of 68
Stuart McGarrity
replied on

Can you paste your code here? : **23**of 68
sasi
replied on

Algorithm 1 Confusion operation Input: Images Output: Confused Image
for each row ’i’ in the matrix ’I’ do Generate random vector KR for each column ’j’ in the matrix ’I’ do rowsum=rowsum + I [i] [j] end for rowmod=rowsum % 2 if rowmod == 0 then for each KR do I=right circular shift(I) end for else for each KR do I=left circular shift(I) end for end if end for for each column ’j’ in the matrix ’I’ do Generate random vector KC for each row ’i’ in the matrix ’I’ do colsum=colsum + I [i] [j] end for colmod=colsum % 2 if colmod == 0 then for each KC do Iscr=up circular shift(I) end for else for each KC do Iscr=down circular shift(I) end for end if end for : **24**of 68
sasi
replied on

send coding : **25**of 68
sachin
replied on

Hello sir, I have equations of motion and i want to form a matrix using these equations by only putting the elements of corresponding function.
As i am new to matlab please guide me how to proceed.
Thanks : **26**of 68
Stuart McGarrity
replied on

Hi Sachin, I assume you are using MATLAB and not Simulink? Here is one simple example you could start with: https://blogs.mathworks.com/loren/2010/03/25/solving-ordinary-differential-equations/ : **27**of 68
Ken
replied on

How can I generate a random square matrix without using any matlab tools? : **28**of 68
Stuart McGarrity
replied on

Hi Ken, Do you mean, using MATLAB but not using MATLAB random number functions like rand or randn? If so, can I ask why you would want to do that? : **29**of 68
sri
replied on

I want to process image matrix in "for loop" in which first loop should consider the matrix 3* 3 , second loop should consider the matrix 2*2, third loop should consider the matrix 2* 2 and again 3*3 and so on...
i.e.first loop-(1:2,1:3)
second loop-(1:2,4:5)
third loop-(1:2,6:8)
fourth loop-(1:2,9:10) and so on...
Can we able write this as coding in Matlab? : **30**of 68
Stuart McGarrity
replied on

Hi Sri, Your first loop iteration has 3 columns, the second 2, the third 3 and the forth 2. Is that correct? So the number of columns is 3 for odd iterations and 2 for even? Or did you make a mistake and it should be 2 each time? : **31**of 68
mỹ phẩM Thái Lan
replied on

you're really a good webmaster. The website loading speed is amazing.
It kind of feels that you are doing any unique trick.
Moreover, The contents are masterpiece. you've done a magnificent job on this subject! : **32**of 68
M Haroon
replied on

I want To add Two matrices in a script file how can i do that. ?? while matrices are been created by using the "for" loop , based on user's requirement to input matrix of any order. : **33**of 68
Stuart McGarrity
replied on

What can't you just use A=B+C ? : **34**of 68
site
replied on

Very goоd article! Wе аre linking to thіs gгeat
article ߋn oᥙr site. Keep uр tҺe great writing. : **35**of 68
Harshini
replied on

can anybody help me out to how to assign array variable to no. of cropped subimages of a image in a for loop? : **36**of 68
Stuart McGarrity
replied on
:

Hi Harshini, Can you write some example code to start? I'm not sure I understand what you want. **37**of 68
ezgi
replied on

I would like to create 500x500 matrix like that [m1 m2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...... ......................................]
[ 0 0 m3 m4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...... .....................................]
[ 0 0 0 0 m5 m6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...... ..................................]..
.. ...
This is 500x500 matrix like that and I need a loop to construct this matrix in MATLAB.
Thank you : **38**of 68
Stuart McGarrity
replied on
:

Hi ezgi, Are m1 and m2 variables? I'd try creating one long row the reshape it. You could start with zeros then index in to assign the variables. **39**of 68
Raisul
replied on

Impulse =961 by 1 double residual =5142 by 32 double
impulse=impulse(:);
residual=v;
[m,n]=size(v);
HD=[];
%
for i=1:m
for j=1:n
HD = impulse(:).*v(i);
end
end
GHD=zscore(HD);
The problem is with the for loop I get the output for the first column only. So I get HD= p by 1 matrix. I want HD =p by 32 matrix. Currently, my impulses elements are multiplied with elements with the rows for the first column only. What modification should I do here to have all elements of impulse to be multiplied with all other columns just as it does for the first column in this loop. So I just need the same operation executed across all columns of v. What might be the nested loop? Should I use another for loop or a while loop inside..I appreciate your skilled solutions. As you see I am a new user, you are helping a lot. : **40**of 68
Sareh
replied on

Hi
Please help me how I write a*b for this matrix a=[1 u u^2 u^3]
0《u《1
And other matrix b=[1 0 0 0;0 0 1 0;-3 3 -2 -1;2 -2 1 1] : **41**of 68
Dami
replied on

Hey,
Please how do I use a four loop statement to perform arithmetic operations such as addition, subtraction and multiplication on a 2 multi-dimensional array.
A = [2, 3, 4, 5; 6, 7, 8, 2; 1, 5, 6, 7] & B = [4, 5, 6, 7; 8, 4, 5, 6; 2, 3, 4, 8] : **42**of 68
Braiki Marwa
replied on

HI, i trained two-class-classification (svmtrain) with 15 features for 18 images and i have many objects in a single image. I want to save single .mat file of features of these images?my problem is when i run this code i have just the variables of last image!!
for n=n1:n2 (number of images)
for k=1:length(B3) (number of objects in a signle image)
Feat(k,:)=[Area_cellule,Perimeter_cellule,Circularity_cellule,Compactness_cellule, Solidity_cellule,Eccentricity_cellule,MajorAxis_cellule,MinorAxis_cellule, Centroid_cellule,Ampl,Contrast_Cellule,Correlation_Cellule,Energy_Cellule,Homogeneity_Cellule];
end
end
save('FeatTrain.mat', 'Feat'); : **43**of 68
stuartmcgarrity
replied on

Hi Braiki, Your Feat variable gets overwritten each n loop. You would need to add another dimension to the matrix to store each image i.e.
Feat(k,:n)=[Area_.... This should work if Feat has the same dimensions for each image. If not, you would need to use a cell array. i.e.
Feat{n}(k:n)=[Area_ : **44**of 68
Oyebee
replied on

Please how do i create a 100 by 100 matrix that looks like this
[ 1 2 3 4 ....100
2 3 4 5...101
3 4 5 6 .... 102}
and so on : **45**of 68
javed
replied on

please tell me how to restructure of broken picture. Please tell me if i can't restructured the photo r picture i have lost my four years study. please help me : **46**of 68
stuartmcgarrity
replied on

Hi Oyebee, What have you tried so far? : **47**of 68
stuartmcgarrity
replied on

Hi Javed, I'm not sure what you mean.Is it related to this post? : **48**of 68
say
replied on

how can i construct a matrix for Cij =1/(xi - yj) ? : **49**of 68
Omololu Makinde
replied on

Could you please show me how to create a 1xmxn multidimensional array with a 3x3 matrix using a for loop? : **50**of 68
Stuart McGarrity
replied on
:

Hi Say, This should work:
x=1:10;y=1:10; % Two row vectors
C=1./(x-y'); % Transpose y into a column **51**of 68
Stuart McGarrity
replied on

Hi Omololu, What have you tried so far? : **52**of 68
Monalisha
replied on

Can I convert a 1:7 matrix to a 1:4 matrix.?
Please help : **53**of 68
Monalisha
replied on

How to convert a 1:7 matrix to 1:4 matrix : **54**of 68
Stuart McGarrity
replied on

Hi Monalisha, Could you give a bit more information? What are the actual dimensions of the matrix before and after? I assume its not 1x7 and 1x4. : **55**of 68
Bhupesh Chandra Gupta
replied on

How to solve this question??
"Use loops and conditional statements to create a 5 by 8 matrix in the value of each element is equal to the square root of the sum of the element's indices unless the element is in an even numbered column or row.The value of an element in an even numbered column or row is equal to the sum of the element's indices squared.(The indices of an element in a matrix are the row number and column number of the elements.) " : **56**of 68
Stuart McGarrity
replied on

Hey Bhupesh, Are you asking for someone to do your homework? : **57**of 68
Ali
replied on

This matrix is 11 × 7. find the sum of all its pairs of elements, odd elements, lines, columns : **58**of 68
Ali
replied on

Please guys help here with this question :
This matrix is 11 × 7. find the sum of all its pairs of elements, odd elements, lines, columns? : **59**of 68
Stuart McGarrity
replied on

Hi Ali,
You can't ask people to do your homework for you. You need to practice on other examples, try something yourself and then if it fails, ask for help. Ask others taking the course too. : **60**of 68
Geoffrey
replied on

No Anyone with solution to this
1 k j m E.g take b2 we will have k,j,j,m etc the same will have k,m,j,m then c will have k,k,j,m etc
2 j m k take c2(b) we will have kjjm the same will have k,m,j,m then c will have kkjm etc
3 j k m one letter k generates 3 options, the second the same when we get to row 2 the same
4 m k j bearing in mind the letters the options generated by the column from 1 to 4 must differ
even if I what to go up to 100. which branch of maths is this? : **61**of 68
Geoffrey
replied on

No Anyone with solution to this
1 k j m E.g take b2 we will have k,j,j,m etc the same will have k,m,j,m then c will have k,k,j,m etc
2 j m k take c2(b) we will have kjjm the same will have k,m,j,m then c will have kkjm etc
3 j k m one letter k generates 3 options, the second the same when we get to row 2 the same
4 m k j bearing in mind the letters the options generated by the column from 1 to 4 must differ
even if I what to go up to 100. which branch of maths is this? : **62**of 68
Janmejaya
replied on

can anyone help me in plotting this equations
n=6.023*10^23;
for r0a=1:100
c0a=(3000/2*n*(pi).^1.5*(r0a).^3);
end
for ca=0.000001:5
g=ca/c0a;
eta=((pi).^0.5)*(g)*exp((g).^2)*(1-erf(g));
end
plot(ca,eta)
Thanking You : **63**of 68
Stuart McGarrity
replied on

Hi Janmejaya,
Is this correct? "for ca=0.000001:5"
How many values should ca have? What is the step size between each one? : **64**of 68
Babtunde Nature
replied on

pls i need to loop the kirkman's schoolgirl problem into a matrix : **65**of 68
Stuart McGarrity
replied on

Hi Babtunde, MATLAB Answers is the best place to pose such a question, if you can't find an answer on Google. If that fails, start by understanding the mathematics of the problem, then coding it in MATLAB. : **66**of 68
zahra hadi
replied on

how do i create a 5x5 matrix with elements given by A(i,j)= 1/(2^i+ 3^j)? : **67**of 68
Stuart McGarrity
replied on

Hi Zahra, Have a look at meshgrid: https://www.mathworks.com/help/matlab/ref/meshgrid.html#bvbngts-1 : **68**of 68
## Recent Comments