why the size function for matrix count less?

1 回表示 (過去 30 日間)
Shiyun Li
Shiyun Li 2020 年 4 月 24 日
編集済み: Deepak Gupta 2020 年 4 月 24 日
Hi
I want to use the size function to check the output array, I expect 12x2 matrix but it shown "rows=8" which is less. Which lead to the next step when I want to use the rows is display an error said Index in position 1 exceeds array bounds (must not exceed 8).
Here is my code. Please let me know if you knwo what 's wrong with it. Thank you.
%print every set of number that sum to target value t
clear;clc;
%input an matrix
a=input('Enter a matrix:');
%check the size of the matrix
n=length(a);
%create an matrix
matrix=[];
%loop through
for r=1:n
for i=1:n
if a(r)+a(i)==12
matrix(r,1)=a(r);
matrix(r,2)=a(i);
end
end
end
%check the size of the matrix
[rows,colns]=size(matrix);
disp(rows);
disp(colns);
for k=1:rows
if matrix (k,1)>=matrix(k,2)
matrix(k,:)=[];
end
end
disp(matrix);
%% when I discard the "check matrix and delect rows part" is display a 12* 2 matrix like this
  1 件のコメント
Shiyun Li
Shiyun Li 2020 年 4 月 24 日
Enter a matrix:[1 3 5 4 6 2 9 12 7 11 8 0]
1 11
3 9
5 7
4 8
6 6
0 0
9 3
12 0
7 5
11 1
8 4
0 12
and when I code to remove the rows with the first number greater than or equal to the second number, it display the error

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

採用された回答

Deepak Gupta
Deepak Gupta 2020 年 4 月 24 日
編集済み: Deepak Gupta 2020 年 4 月 24 日
Hi,
You are getting error, because inside loop, you are deleting rows from the matrix so it's not of the same size as you computed earlier. Better would be to put results in a different matrix.
i.e.
matrix2 = [];
for k=1:rows
if matrix (k,1)<matrix(k,2)
matrix2= [matrix2; matrix(k,:)];
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by