Effacer les filtres
Effacer les filtres

Assigning a value to a certain index according to whether it matches the conditions of an if statement

17 vues (au cours des 30 derniers jours)
This may be a mouthful but I'll do my best to go into depth of what I'm trying to solve.
I have
function [m] = game(n)
Within this, I have a shuffled deck of 52 numbers (which is named A) that have populated a 2 x n+1 vector named numbers.
I also have another vector named sum_numbers that is the sum of each column
sum_numbers = sum(numbers, 1).
Now I need to add a value to a certain location according to whether it matches the following criteria: if the last number in the 2nd row of numbers is greater than 8 and any value within a certain column in sum_numbers is less than 18, a new value will be given to that same column within numbers. So in reality, numbers can be greater than 2 rows. (For this portion I have already created a working code)
I also have to take into account that more than one value may be given to that column subsequently (in order to reach 18 and above) so I have another vector initiated as zeros right now
hit = zeros(1, n)
What I have so far is
for i=1:n
if numbers(2,end) >= 8
if sum_numbers(1,i) < 18
new = A((numbers*2)+3+(sum(hit)))
numbers(3+hit,i) = new
end
end
end
I have tried out my function but the above code does not seem to work because hit isn't populated.
I also don't know how to populate hit. hit should be a 1 x n+1 vector which shows the amount of values given to the respective column(s) that match the criteria so that the values in A are given in subsequent order if need be. (ex. if the 2nd column of numbers has the numbers 3 and 4, which add up to less than 18, it is hit with a 4 and then hit again with the next value 8 and thus the second column in hit should say 2 for 2 'hit' values).

Réponses (1)

Image Analyst
Image Analyst le 23 Fév 2016
Modifié(e) : Image Analyst le 23 Fév 2016
This will do what you said in the first paragraph:
deck = randperm(52); % Shuffle the deck
% Define n
n = 15; % Whatever you want...
% Define "newValue"
newValue = 99; % Whatever you want...
% Distribute deck over 2 rows and n+1 columns
numbers = reshape(deck(1:2*(n+1)), 2, [])
% Sum the columns
columnSums = sum(numbers, 1)
% Check if lower right element (last number in second row) is more than 18
if numbers(2, end) > 8
% Lower right element is more than 8.
% Now see which column sums are less than 18
columnsToReplace = columnSums < 18
% Now replace both rows in numbers of these columns with newValue.
numbers(:, columnsToReplace) = newValue;
end
% Print numbers to command window:
numbers

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by