how to put rand syntax in a matrix operation?

2 views (last 30 days)
raqib Iqbal
raqib Iqbal on 10 Jul 2020
Answered: Deepak on 18 Oct 2024
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

Answers (1)

Deepak
Deepak on 18 Oct 2024
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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!