How to locate the the difference between the max. and min in matrix rows
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
I have a matrix M, whose size is 5 X 3. I located the max. and min. in each rows, then I found their differences. You will find the plot of the difference below. However, it interest me to use a for loop in cases of large sized matrices.
Could someone kindly assit me with a for loop to perform this computation. Thank you
clear all; close all;clc
A=[2 4 7 10 28]; %first
B=[1 3.6 8 11 27];%seccond
C=[0.5 5 9.5 13 32];%third
M=[A' B' C'];
r1=max(M(1,:))-min(M(1,:));
r2=max(M(2,:))-min(M(2,:));
r3=max(M(3,:))-min(M(3,:));
r4=max(M(4,:))-min(M(4,:));
r5=max(M(5,:))-min(M(5,:));
DIFF=[r1 r2 r3 r4 r5];
figure(1)
plot(DIFF);title('Error');ylabel('difference');xlabel('No. of Event ')
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 5 Sep. 2022
You could do this:
% Demo by Image Analyst
% Initialization Steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
A=[2 4 7 10 28]; %first
B=[1 3.6 8 11 27];%seccond
C=[0.5 5 9.5 13 32];%third
M=[A' B' C']
% Method 1: for loop.
[rows, columns] = size(M);
for row = 1 : rows
DIFF(row) = range(M(row, :));
end
plot(DIFF, 'b.-', 'LineWidth', 2, 'MarkerSize', 30);
grid on;
title('Error', 'fontSize', fontSize);
ylabel('Difference', 'fontSize', fontSize);
xlabel('Number of Event', 'fontSize', fontSize)
% Method 2: for loop : using range() function.
DIFF2 = range(M, 2)
Weitere Antworten (1)
dpb
am 5 Sep. 2022
M=[ 2 4 7 10 28;
1 3.6 8 11 27;
0.5 5 9.5 13 32].';
D=range(M,2)
Almost never need loops in MATLAB for such kinds of computations -- and, in this case, don't even have to calculate the min/max; the difference between for arrays is already a builtin function.
NB: the use of the second optional DIM argument to control which dimension of the input array it operates over. This also is a feature of many such MATLAB builtin functions. Read <range> for details; I'd urge you to look at the 'See Also' and 'Functions' links on that page as well to get familiar with basic descriptive statistics functions.
Oh...I forget the above uses the Statistics TB -- never fear, it's only slightly more to do with base product functions as you did--
D=max(M,[],2)-min(M,[],2)
Same caveat; read the details at <max> to see syntax details with it that are slightly different with respect to the 'dim' argument position because the two-argument version is max/min between the two arguments.
1 Kommentar
Siehe auch
Kategorien
Mehr zu Environment and Settings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!