user1642647
user1642647

Reputation: 21

How to change elements in matrices using MATLAB

Starting wish a 7x4 binary matrix I need to change a random bit in each column to simulate error. Have been trying to no avail.

Upvotes: 2

Views: 3194

Answers (2)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Another possibility is to create 4 random numbers in one call, and assign in a vectorized fashion:

rowNumbers = randi(4,[1 4])
A(rowNumbers,:) = ~A(rowNumbers,:);

Upvotes: 1

grungetta
grungetta

Reputation: 1097

A very straightforward way to do this is to use a for loop. It might not be the most efficient approach in MATLAB, but it's probably good enough considering your data set is so small.

Iterate through each of the four columns. On each iteration, randomly chose a number from 1 to 7 to represent the row in that column that you have selected to change. Finally, flip the bit at that row/column. The following code does just this. Assume that "A" is a binary matrix with 7 rows and 4 columns

for col=1:4;                  %// Iterate through each column
    row = ceil(7*rand());     %// Randomly chose a number from 1 to 7 to represent row
    A(row,col) = ~A(row,col); %// Flip the bit at the specified row/col
end

Upvotes: 2

Related Questions