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 Kommentar

Image Analyst
Image Analyst am 7 Apr. 2012
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?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 7 Apr. 2012

0 Stimmen

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 Kommentare

sohrab
sohrab am 7 Apr. 2012
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
Walter Roberson
Walter Roberson am 7 Apr. 2012
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 ()

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by