Adding a row vector into the diagonal of another vector with m, n dimensions using for loop.
Show older comments
Suppose we have a matrix A that is ones(6,8) and another vector b that is [1:10]
i want to make a new array (Add_array) using b and it should have the exact dimensions as matrix A, but with the elements of b in its diagonal using FOR loop. the length of b and A can differ.
After the new array has been made, i have to add it matrix A which has the same dimensions as the new array to get B.
function B = NewArray(A,b)
%NEWARRAY Summary of this function goes here
% Detailed explanation goes here
[m,n] = size(A)
Rows = m;
Columns = n;
Add_array = zeros(Rows,Columns);
for i = 1:Rows
for j = 1:Columns
Add_array(i,j) = Add_array(i,j) + b(1,j);
end
end
B = [Add_array] + [A]
end
This is the code i have written so far^
ans =
2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
This is the result I am getting.^
ans =
2 1 1 1 1 1 1 1
1 3 1 1 1 1 1 1
1 1 4 1 1 1 1 1
1 1 1 5 1 1 1 1
1 1 1 1 6 1 1 1
1 1 1 1 1 7 1 1
This is the expected result.^
I need help with getting the expected result using FOR loops.
thanks!
3 Comments
What's wrong with something like this?
A = randi(9,5,10);
b = 11:20;
% A is not guaranteed to be square
% b is not guaranteed to match size of A
% try to make it fit anyway
s = size(A);
mindim = min(s(1),s(2));
if numel(b) > mindim
b = b(1:mindim);
elseif numel(b) < mindim
b = [b ones(1,mindim-numel(b))];
end
% build array with shortest side on dim1
x = reshape(1:mindim^2,mindim,mindim); % index array
C = ones(sort(s(1:2)));
C(diag(x)) = b;
% transpose if necessary
if s(1) > s(2)
C = C.';
end
C
Humza Khan
on 17 Oct 2021
A = ones(6,8)
b = 1:10
S = size(A);
B = diag(b);
B(end+1:S(1),end+1:S(2)) = 0;
B = A + B(1:S(1),1:S(2))
Accepted Answer
More Answers (0)
Categories
Find more on Operating on Diagonal Matrices 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!