conditional adding of elements to an array

i have the following array: [2 2 4 6 7 16 20 29 48 81 130 163 235 308 414 496 535 521 509 465 355 275 198 120 72 31 16 8 4 2]
what i want to do is if the element of the array is greater than 50, then i replace the element by the the 50 then by the remainder so for example after converting the 10th element the array becomes [2 2 4 6 7 16 20 29 48 50 31 130 163 235 308 414 496 535 521 509 465 355 275 198 120 72 31 16 8 4 2]
how wcan this be done for any array ?

2 件のコメント

James Tursa
James Tursa 2018 年 3 月 17 日
Do this for only the first occurrence, or for all elements? What if the remainder is still greater than 50? Could an element expand into more than two elements?
Ahmad Beydoun
Ahmad Beydoun 2018 年 3 月 17 日
yes the element should be divided till the floor of the division is zero and for all occurrence

サインインしてコメントする。

 採用された回答

James Tursa
James Tursa 2018 年 3 月 17 日

0 投票

A = your data vector
n = whatever (e.g., 50)
result = cell2mat(arrayfun(@(x)[repmat(n,1,floor(x/n)),rem(x,n)],A,'uni',false));

2 件のコメント

Ahmad Beydoun
Ahmad Beydoun 2018 年 3 月 17 日
thank you !!! you have no idea how much i appreciate your help
James Tursa
James Tursa 2018 年 3 月 17 日
You should use Rik's answer since he covers the case for exact multiples!

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2018 年 3 月 17 日

0 投票

Not the most beautiful code I've ever written, but this should do what you want. I tested it as well with [0 50].
a=[2 2 4 6 7 16 20 29 48 81 130 163 235 308 414 496 535 521 509 465 355 275 198 120 72 31 16 8 4 2];
a=num2cell(a);
fun=@(x) [repmat(50,1,floor(x/50)) repmat(mod(x,50),1,mod(x,50)~=0)];
result=cellfun(fun,a,'UniformOutput',false);
result=cell2mat(result);

1 件のコメント

Ahmad Beydoun
Ahmad Beydoun 2018 年 3 月 17 日
thank you rick !! much appreciated !!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by