Adding a row vector into the diagonal of another vector with m, n dimensions using for loop.
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Stephen23
2021년 10월 17일
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))
채택된 답변
DGM
2021년 10월 17일
편집: DGM
2021년 10월 17일
Actually, using a loop was pretty dang simple, now that I tried it.
A = randi(9,5,10);
b = 11:20;
diagonalthing(A,b)
diagonalthing(A.',b(1:3))
function C = diagonalthing(A,b)
% synopsis goes here bla bla bla
s = size(A);
mindim = min(s(1),s(2));
C = ones(s);
for k = 1:min(mindim,numel(b))
C(k,k) = b(k);
end
end
댓글 수: 2
DGM
2021년 10월 17일
They could be avoided, but without resorting to other potentially more complex or forbidden functions, things get kind of unreasonably ridiculous.
Depending on what's forbidden, you might be able to get away with:
x = 1:10;
% numel() can be avoided by using size
n = size(x(:),1)
% min() can be avoided using sort
mn = sort(x(:),'ascend');
mn = mn(1)
I kind of doubt sort() is allowed if min() isn't allowed. You could always use a loop i guess.
% or you could use a loop
mn = x(1);
for k = 1:numel(x) % have to replace numel again
if x(k) < mn
mn = x(k);
end
end
mn
Of course, it would be desirable to write this as a function so that you don't have to repeat code -- but I imagine you aren't allowed to do that either. That's the way these garbage assignments seem to go.
I don't know which aspect ot these assignments bothers me more, instructing students on how to write the least efficient code possible, or prohibiting students from acting on initiative and learning beyond the lesson.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!