MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#" onclick="window._kiq.push(['set', { 'event': 'Turn off MT' }]);">ここ</a>」をクリックしてください。

0

How to generate a matrix with number of lines inserted from keyboard

Fiddl Sticks さんによって質問されました 2019 年 6 月 17 日 17:02
最新アクティビティ Star Strider
さんによって コメントされました 2019 年 6 月 17 日 22:01
I have to generate a matrix with i lines and j=i+1 collumns whose elements:
=2 if i=j;
=-1 if | i -j |=1;
=0 otherwise.
Here's my attempt at solving this problem:
prompt='Insert number of lines';
i=input(prompt)
j=i+1
% getting the number of lines and collumns
if i==j
A=2*ones(i,j);
end
% checking the first condition for i and j
else if abs(i-j)==1
A=-1*ones(i,j);
end
% checking the second condition for i and j
else
A=zeros(i,j)
% checking the third condition for i and j
end
end
A
% displaying matrix A
And I get this error when I try run it:
else if abs(i-j)==1
|
Error: Illegal use of reserved keyword "else".
I don't understand what I'm doing wrong.

  0 件のコメント

サインイン to comment.

1 件の回答

回答者: Star Strider
2019 年 6 月 17 日 17:36
 採用された回答

You had too many end statements. They were defining very short if blocks, and so some of those blocks did not begin correctly as a result.
Your code still has problems (it is not doing what you want it to). Since this appears to be a homework assignment, I will defer to you to get it running correctly.
This runs:
if i==j
A=2*ones(i,j);
% checking the first condition for i and j
elseif abs(i-j)==1
A=-1*ones(i,j);
% checking the second condition for i and j
else
A=zeros(i,j)
% checking the third condition for i and j
end

  8 件のコメント

Star Strider
2019 年 6 月 17 日 20:56
It depends on the conditions.
The ‘logical indexing’ approach I used here would likely work.
For example to set all elements of ‘A’ equal to 5 for K1 > K2:
i = 5;
j = i + 1;
A = zeros(i,j);
A = 5*(K1 > K2)
produces:
A =
0 0 0 0 0 0
5 0 0 0 0 0
5 5 0 0 0 0
5 5 5 0 0 0
5 5 5 5 0 0
But that's not all elements of A equal to 5.
This would be all elements of A equal to 5:
A =
5 5 5 5 5 5
5 5 5 5 5 5
5 5 5 5 5 5
5 5 5 5 5 5
5 5 5 5 5 5
Star Strider
2019 年 6 月 17 日 22:01
In my example, I did not set all the elements equal to 5. I set only the elements where K1>K2 equal to 5. That was the point of the example.
Perhaps I should have phrased it: ‘... to set all elements of ‘A’ for K1 > K2 equal to 5

サインイン to comment.



Translated by