how to put rand syntax in a matrix operation?

조회 수: 2 (최근 30일)
raqib Iqbal
raqib Iqbal 2020년 7월 10일
답변: Deepak 2024년 10월 18일
cellular=1:100
resource=[1 8;2 12;3 7;4 18;5 17]
ROM = [cellular(1:size(resource,1)).', sortrows(resource, 2)];
ROM = ROM(ROM
(:, end) > 5, :)
what changes i have to do,,if i want "cellular value choose the resource column2 value with >5 randomly(but onle column2 value can be choosed by cellular value max 5 times)nd after choosing display will be like :--
1 column:-cellular value column
2nd column:--resource column1
3rd column:--resource 2nd column

답변 (1개)

Deepak
Deepak 2024년 10월 18일
From my understanding, you have written MATLAB code to define the “ROM” matrix by pairing the first few values from the “cellular” vector with the “resource” matrix, sorted by its second column.
Now, you want to modify it so that each “cellular” value can randomly choose rows from the “resource” matrix where the second column is greater than 5. Also, the output matrix should contain three columns in the following order:
  1. cellular value
  2. “resource column 1
  3. resource column 2
To accomplish this, we can first filter the “resource” matrix to include only those rows where the second column is greater than 5. Then, we can select a random number between 1 and 5 using the randi” function in MATLAB. For each cellular value, we can randomly select up to 5 indices from the filtered “resource” matrix by using the “randperm” function. Finally, we can build the result matrix by appending the selected “resource” rows along with the corresponding “cellular” value.
Please find below the MATLAB code to achieves the same result:
cellular = 1:100;
resource = [1 8; 2 12; 3 7; 4 18; 5 17];
% Filter resources with column 2 values greater than 5
filteredResource = resource(resource(:, 2) > 5, :);
result = [];
for i = 1:length(cellular)
% Randomly select up to 5 resources for each cellular value
numSelections = randi([1, 5], 1);
selectedIndices = randperm(size(filteredResource, 1), min(numSelections, size(filteredResource, 1)));
% Append the selected resources to the result
for j = selectedIndices
result = [result; cellular(i), filteredResource(j, :)];
end
end
disp('Cellular | Resource Col1 | Resource Col2');
disp(result);
Please find attached the documentation of functions used for reference:
I hope this contributes to resolving the issue.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by