- “cellular” value
- “resource” column 1
- “resource” column 2
how to put rand syntax in a matrix operation?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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:
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!