how to find the largest scalar in array with 2 ways?
3 次查看(过去 30 天)
显示 更早的评论
采纳的回答
John BG
2017-8-31
Hi AnhThu Le
Let's say you have the following matrix
A=randi([1 10],randi([1 5],1,1),randi([1 5],1,1),randi([1 5],1,1))
A(:,:,1) =
5 8 2 3 2
4 4 10 4 7
10 3 10 9 8
4 5 6 1 7
2 1 1 1 5
A(:,:,2) =
6 2 10 4 7
3 4 8 6 4
8 7 5 6 9
2 8 5 9 6
7 1 5 8 4
A(:,:,3) =
10 3 2 4 10
9 4 3 10 5
6 5 2 5 2
7 3 3 2 3
6 9 5 10 5
then,
1.
copy in case you want to keep the original variable
maxA=A;
2.
keep applying max to end up with the largest scalar only
for k=1:1:numel(size(A))
maxA=max(maxA);
end
maxA =
10
3.
a shorter way is simply squeeze the matrix to single file and get the max
max(A(:))
ans =
10
Do you mean by '2 ways' that the dimension of the arrays is 2?
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG
0 个评论
更多回答(1 个)
Jan
2017-8-31
"Largest scalar". Sounds like a maximum. Then take a look into the documentation.
docsearch maximum
The first hits sound strange: "movmax", "cummax", "namelengthmax". Not really useful. But hope, that MathWorks was smart. Open the first link, scroll down and look into the "See also" line. You find similar commands there. And here you get "max". Click on the command to open the docs, or type this directly (guessing this name is not too difficult):
doc max
The output of this command would be fine for a vector, but you have a matrix. Then the maximum for each column is replied.
Read the "Getting Started" chapters again - how to convert a matrix into a vector. Please do this - it will be very useful. You cannot ask the forum for all basics. You will find A(:).
You want a 2nd way? Try a loop: Use a for loop to step through all elements of A. Start with the value v = -Inf. If the current element is larger, store it in v. At the end v will contain the maximum.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!