Filling A matrix with characters in a loop

Hello i want to fill a matrix with characters in a loop, for example i want to have a variable 'n' which my loop starts with 1 and ends with 'n' and fill a matrix with one column and 'n' rows with characters like 's' in some rows in a condition and 'us' in another condition, in the other word; i dont know how i can fill a char matrix in a loop

1 Comment

Will the conditions change once you're into the loop, or is the condition the same for the whole loop? Is it a 2D matrix? If so, which column do you want to assign?

Sign in to comment.

 Accepted Answer

If you need to fill some positions with 'us' then you need a string at each position rather than a character . You will need to use cell arrays for that, or else use a matrix with one higher dimensions together with blank padding.
for col = 1 : n
if rand() <= 0.8 %the main condition
YourMatrix(:,col) = 's'; %fill this column
else %the alternate condition
YourMatrix(:,col) = 'u'; %alternate fill
end
end

2 Comments

thank you for your helpful answer, now i have another problem, i want to have a matrics which one of its columns has strings and another columns are numbers, something like this:
1 0.3565 st
2 0.6456 ust
how could i have something like this? the third column of this matrics is that matrix which i asked you before
The only way to do this is to use a cell array.
YourMatrix = num2cell(rand(n,2)); %two columns of numbers in cell
for row = 1 : n
if rand() <= 0.8 %the main condition
YourMatrix{row,3} = 'st'; %fill this entry
else %the alternate condition
YourMatrix{row,3} = 'ust'; %alternate fill
end
end
Notice the use of {} instead of ()

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!