What is wrong with my code?

Hi. I am trying to write a function that takes two inputs (N and n) and return a n by n array at the top right corner of N. So far i have:
function M = top_right(N,n)
M = N(1:n, 1:n);

回答 (3 件)

Star Strider
Star Strider 2016 年 8 月 5 日

1 投票

I’m not exactly certain what you want to do.
See if this works for you:
N = 6; % Argument
n = 3; % Argument
M = zeros(N); % Create ‘M’
M(1:n, N-n+1:N) = 1 % Set Top Right Corner To ‘1’
M =
M =
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

4 件のコメント

Alexandra Huff
Alexandra Huff 2016 年 8 月 5 日
I think that it what I want however, im trying for a more general code, not something as specific as that.
Star Strider
Star Strider 2016 年 8 月 5 日
Another approach:
N = 6; % Argument
n = 3; % Argument
M = randi(99,N); % Create ‘M’
M(1:n, N-n+1:N) = rand(n) % Set Top Right Corner To ‘rand’
79 68 70 0.119 0.34039 0.75127
95 76 4 0.49836 0.58527 0.2551
65 74 28 0.95974 0.22381 0.50596
4 39 5 4 49 68
85 65 10 44 45 65
93 17 82 38 64 17
Alexandra Huff
Alexandra Huff 2016 年 8 月 5 日
The first way is what I want but I am trying to figure out how to do it without defining specifically what N and n is. Does that clarify what I am looking for better? So, I am trying to take two inputs N and n, where N's dimension is always greater than or equal to n. Then the function returns a n by n square array at the top right corner of N.
Star Strider
Star Strider 2016 年 8 月 5 日
I don’t see any way to do what you want without specifically defining ‘N’ and ‘n’ unless you do it randomly:
N = randi(8); % Argument
n = randi(N-2); % Argument
M = zeros(N); % Create ‘M’
M(1:n, N-n+1:N) = 1 % Set Top Right Corner To ‘1’
I’m keeping the matrices small for convenience. You can also define ‘n’ as:
n = randi(N-randi(N-1));
That way, you don’t have to define anything specifically, since all the parameters are random integers.

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

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 5 日

0 投票

idx=sub2ind(size(N),1:n, 1:n)
M=N(idx)
Walter Roberson
Walter Roberson 2016 年 8 月 5 日
編集済み: Walter Roberson 2016 年 8 月 5 日

0 投票

M = N(1:n, end-n+1:end);

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2016 年 8 月 5 日

編集済み:

2016 年 8 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by