How to add values to an array and how to add values to a table without overlapping them

조회 수: 2 (최근 30일)
I want to make an array of random values.
just put the value in the array but it just gets overwritten, I want to add a value to a random array to create an array what functions are there?
And in that arrangement, I want to put it in the table as a value
How do I create a table in order of values in an array without overlapping values?

답변 (1개)

Shivam
Shivam 2024년 9월 5일
Hi 주영,
You can use the random function e.g. randi to generate a random number and keep appending that number into an array for certain number of iterations.
% Initial empty array
randomArray = [];
% Append random values to the array for 10 iterations
for i = 1:10
newValue = randi(100); % Random integer between 1 and 100
randomArray = [randomArray, newValue]; % Append to the array
end
Also, use the unique function to remove duplicates from the array.
uniqueArray = unique(randomArray);
Post this, you can convert the array into a MATLAB table using array2table function:
T = array2table(uniqueArray', 'VariableNames', {'RandomValues'});
% Display the table
disp(T);
RandomValues ____________ 16 33 35 50 53 56 61 83 85
You can visit these documentation links of randi, unique and array2table function to know more:
I hope it helps you achieve the desired behaviour.
Thanks
  댓글 수: 1
Stephen23
Stephen23 2024년 9월 5일
편집: Stephen23 2024년 9월 5일
"You can use the random function e.g. randi to generate a random number and keep appending that number into an array for certain number of iterations."
Doing this in a loop and expanding the output array on each iteration is very inefficient. Much better:
Best would be to generate them all at once in an array of the correct size:
randi(100,1,10)
ans = 1x10
96 97 69 27 55 46 57 44 59 90
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
"Also, use the unique function to remove duplicates from the array."
Thus leaving an unknown number of values. Use RANDPERM if duplicates must be excluded:
randperm(100,10)
ans = 1x10
81 75 100 71 27 18 49 96 76 14
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by