sort 2 matrices for minimum numbers sum and divide them
Show older comments
I have r = [ 1 3 4 5 ......n]
and x = [ 5 8 9 4 ......n]
I will like to do this computation
when m = 1
sort the lowest number of r and divide it with the lowest number of x till the end n
for example =[ 1/4, 3/5, 4/8, 5/9.......n]
when m = 2
= [(1 + 3) / (5 + 4) , (4 +5)/(8+9) , ...........n]
when m =3
=[ (1 + 3 + 4)/( 4 + 5 + 8),................n]
Thanks for your help in advance
Tino
Accepted Answer
More Answers (3)
Raj
on 4 Jun 2019
I am assuming n is a multiple of m. In that case this works:
r=sort(r);
x=sort(x);
m=input('enter value of m:');
if m==1
for ii=1:numel(r)
Answer(1,ii)=r(1,ii)/x(1,ii);
end
Answer
elseif m==2
Answer(1,1)=(r(1,1)+r(1,2))/(x(1,1)+x(1,2));
for ii=3:2:numel(r)
Answer(1,(ii+1)/2)=(r(1,ii)+r(1,ii+1))/(x(1,ii)+x(1,ii+1));
end
Answer
elseif m==3
Answer(1,1)=(r(1,1)+r(1,2)+r(1,3))/(x(1,1)+x(1,2)+x(1,3));
n=0;
for ii=4:3:numel(r)
Answer(1,(ii-n)/2)=(r(1,ii)+r(1,ii+1)+r(1,ii+2))/(x(1,ii)+x(1,ii+1)+x(1,ii+2));
n=n+1;
end
Answer
else
disp('Invalid Value of m')
end
There may be better and optimized way of doing this also.
P.S: How about adding a 'Homework' tag next time and showing what you attempted in addition to 'Hope to hear from you soonest'? Everybody wil not be as free as i am today! Cheers!!
Pullak Barik
on 4 Jun 2019
Edited: Pullak Barik
on 4 Jun 2019
Hi!
I assume that r and x are just vectors, and not matrices with more than one dimension.
I guess the following function will work for you-
function result = sort_sum_and_divide(r, x, m)
r = sort(r);
x = sort(x);
n = length(r);
if(length(r) == length(x)) %To check if the input is wrong
i = 1:m:n;
if(i(end) + m - 1 > n)
i(end) = []; %To drop the elements at the end if they can not be grouped
end
result = zeros(1, length(i)); %preallocation of result array
for idx = 1:length(i)
result(idx) = sum(r(i(idx):i(idx)+m-1))./sum(x(i(idx):i(idx)+m-1));
end
else
disp('Length of r and x are not the same');
end
end
2 Comments
@Pullak Barik: note that concatenation onto the result array like that is not considered good practice, and detrimentally affects efficiency:
The MATLAB documentation recommends preallocating arrays before the loop:
Pullak Barik
on 4 Jun 2019
Ya, I could preallocate my result array. Thanks.
Andrei Bobrov
on 4 Jun 2019
Edited: Andrei Bobrov
on 4 Jun 2019
1 vote
m = 3;
r = [ 1 3 4 5 30];
x = [ 5 8 9 4 78];
out = funt(r,x,3);
function out = funt(r,x,m)
ad = nan(mod(-numel(r),m),1);
a = sort(cat(3,[r(:);ad],[x(:);ad]));
b = sum(reshape(a,m,[],2),'omitnan');
out = b(:,:,1)./b(:,:,2);
end
add
rx = [1
3
4
5
6
7
8
9
2
6];
m = 2;
rrxx = sum(sort(reshape([reshape(rx,[],2);nan(mod(-numel(rx)/2,m),2)],...
m,[],2)),'omitnan');
out = rrxx(:,:,1)./rrxx(:,:,2);
Categories
Find more on Time-Frequency Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!