Writing the built in matlab function in simple code(like for loop, etc.)

1 回表示 (過去 30 日間)
Jimmy cho
Jimmy cho 2021 年 1 月 23 日
編集済み: Adam Danz 2021 年 1 月 24 日
Hi guys,
I'm trying to do the same concept of what my code below does, but in a simple approach with different way.
My code in MATLAB is:
y=[1 2 3 4]; %first input
OccurancesParameter= 5; % second input , it's always unsigned integer number greater than zero - it's number occurances for each value in the array y
output=repelem(y, OccurancesParameter); % gives me an array according to the repeated Occurance parameter ..
So I want to do the same concept of what my code above does, but simple approach/way in MATLAB, like using for loop or any other simple way, and not using the built in function repelem().
Could anyone please help me out on this? appreciated!

採用された回答

Image Analyst
Image Analyst 2021 年 1 月 23 日
Jimmy, try this:
y=[1 2 3 4]; % First input
OccurancesParameter= 5; % second input , it's always unsigned integer number greater than zero - it's number occurances for each value in the array y
output=repelem(y, OccurancesParameter); % gives me an array according to the repeated Occurance parameter ..
y2 = zeros(1, length(y) * OccurancesParameter);
for k = 1 : length(y)
thisy = y(k);
for k2 = 1 : OccurancesParameter
index = (k - 1) * OccurancesParameter + k2;
y2(index) = thisy;
end
end
y2 % Display in command window

その他の回答 (1 件)

Adam Danz
Adam Danz 2021 年 1 月 23 日
編集済み: Adam Danz 2021 年 1 月 24 日
You can use implicit expansion which is supported in Matlab r2016b and later (more info).
y=[1 2 3 4];
OccurancesParameter= 5;
m = y(:)' .* ones(OccurancesParameter, 1);
output = m(:)'
output = 1×20
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
For Matlab releases prior to r2016b,
y=[1 2 3 4];
OccurancesParameter= 5;
m = bsxfun(@times,y(:)', ones(OccurancesParameter, 1));
output = m(:)'
output = 1×20
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by