Using loops in matrix
13 views (last 30 days)
Show older comments
Please help. give any tips or suggestions that you can
I am trying to create a script that is 3x3 matrix of random integers between 1 and 4. But, I need this matrix to produces the output matrix B which is also a 3x3 matrix. Calculates the elements of matrix B such that: the values of B along the diagonal are equal to the respective elements in A and the values in each element of B not along the diagonal are equal to the sum of the values in the respective row and column of A.
I have the following for A, but am confused on how to do the loop to create B.
A= randi (4,3,3);
6 Comments
James Tursa
on 16 Nov 2020
To generalize it for a 2D matrix of any size:
[M,N] = size(A); % get the row and column size of A
for i=1:M % run the row loop up to M
for j=1:N % run the column loop up to N
:
etc.
Answers (2)
James Tursa
on 17 Nov 2020
Edited: James Tursa
on 17 Nov 2020
So your latest post is a really good effort! A couple of things you are missing from the instructions:
"create a new variable N as the first line of code"
So you first line of code should be:
N = 3; % or whatever value you want, or maybe use the input( ) function here
"N defines the size of matrix A"
"A is created using N"
So you need to create A using what you had in your original post but using N instead of 3, namely
A = randi(4,3,3); % change this to use N instead of hard coding 3
"change your code that determines B and generalize it to work for any N"
So change this line to generalize it:
B = zeros(3); % change this to use N instead of hard coding 3
The entire instructions about generalizing the code are basically to use N instead of 3. And also since you are using size(A,1) and size(A,2) that is generalizing also (although because of how you created A you could have used N here instead of size(A,1) and size(A,2) ... either one is correct).
David Hill
on 16 Nov 2020
A=randi(4,3);
[b,c]=meshgrid(sum(A),sum(A,2));
B=(b+c-A).*(~eye(3))+diag(diag(A));
1 Comment
James Tursa
on 16 Nov 2020
Edited: James Tursa
on 16 Nov 2020
Seriously? This is a beginning programming homework assignment ...
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!