Am trying to reduce a vector by summing some elements in the vector to form another vecter

example if v=[40,34,10,8,6,2] then the new vector will make 40 to be the reference point. after comparing each element the new vector will be N=[40,34,26]

6 Kommentare

What are the rules about which elements are to be retained and which are to be summed?
Is the rule that you are to stop summing if the sum would exceed the reference value?
Bashir - why have you decided to sum the elements 10, 8, 6, and 2? Why not include 34 and reduce your v to just
N = [40 50];
Do you just continue adding the elements until their sum is less than 40 (the reference number)? Do you always assume that your array is already sorted in decreasing order?
Whatever the rules are, a non-loop solution will very likely involve a call to cumsum.
I wanted to make 40 as the highest value that is why I don't want 34 to be included in the summation. so that is why I wanted to start with the lowest value up.
I suspect this is a case where a loop would be the easiest.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

b = cumsum(hankel(v));
k = max(b .* (b <= 40));
N = k(cumsum(k) <= b(end,1));
or
t = cumsum(hankel(v));
t = max(t.*(t <= 40));
N = t(cumsum(t) <= sum(v));

2 Kommentare

pls if I have a vector a=[30.85,4.11,6.17,2.51,2.28]; b=sum(a)/numel(a); I want to find the closes value to the average b and its indices, what will I do?
a=[30.85,4.11,6.17,2.51,2.28];
b = mean(a);
t = a < b;
vals = a(t);
indices = find(t);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by