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

Image Analyst
Image Analyst 2012년 4월 7일
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?

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2012년 4월 7일

0 개 추천

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

sohrab
sohrab 2012년 4월 7일
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 ()

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by