Newbie help for matlab
古いコメントを表示
how do i write a function that has two 3x3 input matrices and in output it gives new matrix that contains the rows of the input that has the least sum .I.e. a=[1 2 3;2 3 4; 3 4 5] and b=[1 2 3;2 3 4; 3 4 5] then print c=[1 2 3;1 2 3] . I have the logic in my head but i can't code it in matlab since i have only 1 lesson on it. Thanks
採用された回答
その他の回答 (1 件)
Image Analyst
2014 年 10 月 8 日
Try this:
% Create sample data
a=[1 2 3;2 3 4; 3 4 5]
b=[3 2 1;2 3 4; 2, 2, 2]
% Find the sums over columns for both arrays.
columnSumsA = sum(a, 2)
columnSumsB = sum(b, 2)
% Find the overall minimum sum.
MinSumOverall = min([columnSumsA; columnSumsA])
% Find out where (what row) that sum occurs in matrix a & b.
rowLocationInA = find(columnSumsA == MinSumOverall)
rowLocationInB = find(columnSumsB == MinSumOverall)
% Construct C from those rows extracted out from a and b
c = [a(rowLocationInA,:);, b(rowLocationInB, :)]
In the command window, you can see the individual steps results:
a =
1 2 3
2 3 4
3 4 5
b =
3 2 1
2 3 4
2 2 2
columnSumsA =
6
9
12
columnSumsB =
6
9
6
MinSumOverall =
6
rowLocationInA =
1
rowLocationInB =
1
3
c =
1 2 3
3 2 1
2 2 2
2 件のコメント
Nikola
2014 年 10 月 8 日
Image Analyst
2014 年 10 月 8 日
編集済み: Image Analyst
2014 年 10 月 8 日
That's what it would do if the sum occurred only once. But look at my example. You can have a sum of 6 with 1,2,3 or with 2,2,2. Well, what if both of those occur in "b"? Which row(s) do you extract? I extracted both/all. If you wanted to take just first one, or the last one, you could do that. What do you want to do if b looks like this:
b =
3 2 1
2 3 4
2 2 2
such that the min sum occurs on more than 1 row?
[EDIT] To take the first one, do this:
% Create sample data
a=[1 2 3;2 3 4; 3 4 5]
b=[3 2 1;2 3 4; 2, 2, 2]
% Find the sums over columns for both arrays.
columnSumsA = sum(a, 2)
columnSumsB = sum(b, 2)
% Find out where (what row) that sum occurs in matrix a & b.
[minSumA, rowLocationInA] = min(columnSumsA)
[minSumB, rowLocationInB] = min(columnSumsB)
% Construct C from those rows extracted out from a and b
c = [a(rowLocationInA,:);, b(rowLocationInB, :)]
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!