Index exceeds the number of array elements.

Hello everyone. I have a problem with error "Index exceeds the number of array elements. Index must not exceed 10.". I understand why theres an error but dont know how to work around it. The error message shows up because Iam comparing a value to nothing, but I need to do something with the last of the duplicates, which in this case is the last value of the array. I tried to explain the program and what it needs to do in each row.
x = [25 10 10 12 10 25 13 25 25 11]'; %input
x = sort(x,'descend'); %sorting from largest to smallest
x_pocet=numel(x); %number of values
dupli = grouptransform(x,x,@numel); %finding duplicates
for i=1:x_pocet %for i from 1 to number of values
if dupli(i)<=1 %if the value isnt a duplicate calculate profit
trzba = i*(x(i));
fprintf('\n Pro cenu %d. je trzba %d. \n',x(i),trzba)
else if dupli(i)>=1 && x(i)==x(i+1) %if the value is a duplicate and the value is same as the next one do nothing
else %if the value is a duplicate but is the last of the duplicates calculate profit
trzba = i*(x(i));
fprintf('\n Pro cenu %d. je trzba %d. \n',x(i),trzba)
end
end
end
If anyone could help me with solving the problem, it would be much appriciated.

 採用された回答

Torsten
Torsten 2021 年 12 月 18 日
編集済み: Torsten 2021 年 12 月 18 日

0 投票

x = [25 10 10 12 10 25 13 25 25 11]';
x = sort(x,'descend');
[xc,xr] = groupcounts(x);
xc = fliplr(xc);
xr = fliplr(xr);
trzba = -Inf;
element = 0;
for i = 1:numel(xr)
element = element + xc(i);
trzba = max(trzba,element*xr(i));
end
trzba

3 件のコメント

Matyas Lehky
Matyas Lehky 2021 年 12 月 18 日
Let me try to explain what the output should be a bit better.
Basically what the script should do is:
1) Take the number 25 (highest) and multiply by 4 = 100.
2) Take the number 13 and multiply by 4+1 (4 from the 25s and 1 because there is one 13) = 65
3) Take the number 12 and multiply by 4+1+1 (4 from 25s, 1 from 13s, 1 from 12s) = 72
4) Take the number 11 and multiply by 4+1+1+1 (4 from 25s, 1 from 13s, 1 from 12s, 1 from 11s) = 77
5) Take the number 10 and multiply by 4+1+1+1+3 (4 from 25s, 1 from 13s, 1 from 12s, 1 from 11s,3 from 10s) = 100.
Then when I feed the script random values it should output the highest number which in case of numbers above would be 100.
Torsten
Torsten 2021 年 12 月 18 日
I changed the code from above according to your explanation.
Matyas Lehky
Matyas Lehky 2021 年 12 月 18 日
Briliant! Thank you very much.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2021b

質問済み:

2021 年 12 月 18 日

コメント済み:

2021 年 12 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by