MATLAB Answers

Matlab question, very stuck

21 ビュー (過去 30 日間)
James Harrison
James Harrison 2021 年 1 月 10 日
コメント済み: Image Analyst 2021 年 1 月 11 日
I am very stuck with this question, any help would be appreciated.
function [New_Matrix] = sequence_matrix(n)
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
if n ==1
v=2
elseif n==2
v=3
elseif n>=3
i(n) = 2*v(n-1) + 3*v(n-2)
i=zeros(n,n);
m = i;
i(1:n+1:end) = v
end

  0 件のコメント

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2021 年 1 月 10 日
Close but not quite. Try it this way:
function [New_Matrix] = sequence_matrix(n)
% Detailed explanation goes here
New_Matrix = zeros(n);
v = 2;
if n >= 2
v = [2, 3];
end
if n >= 3
for k = 3 : n
v(k) = 2*v(k-1) + 3*v(k-2)
end
end
for k = 1 : n
New_Matrix(k, k) = v(k);
end
end

  2 件のコメント

James Harrison
James Harrison 2021 年 1 月 10 日
Yes this is almost perfect. I just have to make it say 'Error. Invalid input' if the value entered is less than 2
Image Analyst
Image Analyst 2021 年 1 月 11 日
At the beginning, after you assign New_Matrix, say
if n < 2
warningMessage = sprintf('Error. Invalid input.\nYou entered n = %d.\nn must be 2 or greater', n);
uiwait(errordlg(warningMessage));
return;
end

サインインしてコメントする。

その他の回答 (1 件)

William
William 2021 年 1 月 10 日
Your program seems to be a little uncertain about whether v is a number or a vector, and it also doesn't assign the values correctly into the diagonal of the matrix i(). However, the general sequence of operations is correct. Let me suggest the following:
  1. Create the vector v as a vector with n elements, using v = zeros(1,n);
  2. Fill in the values of v(j), with v(1) = 2, v(2) = 3, and v(j) = 2*v(j-1) + 3*v(j-2) for all j > 2;
  3. Then put the values of v into the diagonal of a matrix I using I = diag(v);
Let me know how it turns out!

  0 件のコメント

サインインしてコメントする。

カテゴリ

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by