How to compare two columns of every row and display them?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Daven Artajo
am 3 Dez. 2021
Kommentiert: Daven Artajo
am 4 Dez. 2021
TASK 1: So I have a simple vector and I needed to compare if first column is greater than the second column.
N = [1042, 713, 4, 42]
N(1); , N(2);
if N(1) > N(2)
disp("increasing"); % if column 1 is greater it is increasing
else
disp("decreasing"); % if column 2 is greater it is decreasing
end
TASK 2: This time I need to calculate the sum of the first 3 columns and also print the last column. Repeating each row. Now say the vector has become a 4 x 4.
M = [1042 713 4 42; 30 48 0 12; 4 160 12 1; 1 111 2 0]
extra = M(:, 4);
sum = M(:, 1) + M(:, 2) + M(:, 3);
% I want to print this in a format of:
fprintf('Sum of values: %.0f, extra value: %.0f\n', [sum(:),extra(:)].');
TASK 3: Now I need to extend Task 2 by repeating Task 1 of comparing the first column to the second column of each row.
The format will be like this: Sum of values: "val1", extra value: "val2" increasing (*or decreasing)
What I've came up with is this and so far it hasn't been working since it prints decreasing for every row even tho first one is increasing.
A = M(:, 1);
B = M(:, 2);
disp("The cases are: ");
M;
chan = M(:, 4);
for sum3 = M(:, 1) + M(:, 2) + M(:, 3);
if A > B
% disp("increasing");
fprintf('Sum of values: %.0f, extra value: %.0f increasing\n'...
,[sum3(:),chan(:)].');
else
% disp("decreasing");
fprintf('Sum of values: %.0f, extra value: %.0f decreasing\n'...
,[sum3(:),chan(:)].');
end
end
How to simplify or code this properly? Thank you :)
0 Kommentare
Akzeptierte Antwort
DGM
am 3 Dez. 2021
Well, this is what I did.
% PART 2
M = [1042 713 4 42; 30 48 0 12; 4 160 12 1; 1 111 2 0]
extra = M(:, 4);
sum3col = sum(M(:,1:3),2); % don't overload sum()
fprintf('Sum of values: %.0f, extra value: %.0f\n', [sum3col(:),extra(:)].');
% PART 3
deltastr = {'decreasing','unchanged','increasing'};
deltastridx = sign(diff(M(:,1:2),1,2))+2;
% loop can be avoided, but it gets messy with mixed array types
for r = 1:size(M,1)
fprintf('Sum of values: %.0f, extra value: %.0f, %s\n', ...
sum3col(r),extra(r),deltastr{deltastridx(r)});
end
The loop can be avoided, but the mixed numeric/cell array inputs make it a mess that makes for at least as much clutter.
3 Kommentare
DGM
am 3 Dez. 2021
I was working on the assumption that each row represents a sequence from left to right (in the order of their subscripts). Under that assumption, [1042 713] is a decreasing series.
If you want to assume a different convention, then yeah. You can either just flip deltastr()
deltastr = {'increasing','unchanged','decreasing'};
or you can invert the index vector.
deltastridx = 2-sign(diff(M(:,1:2),1,2));
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!