フィルターのクリア

How to add values into Matlab matrix and not overwrite it

11 ビュー (過去 30 日間)
Lara Lirnow
Lara Lirnow 2017 年 2 月 17 日
コメント済み: Lara Lirnow 2017 年 2 月 18 日
I have to insert values from a for loop into the matrix, but the values are all the time getting overwritten, so only last values are added into the matrix. What is the way to add every value to the matrix inside a for loop without overwriting?
My code is this:
%reading the file
list = fopen('intervals.txt','r');
C=cell(size(list))
for k=1:length(list)
content = fgets(list(k))
d= strsplit(content,',')
for n=1:length(d) % d contains 25 elements
B = zeros(n,1); % preallocate, results output
y=d{n}
z= strsplit(y,' ')
start=z{1}
stop=z{2}
start1 = str2num(start)
stop1 = str2num(stop)
B = [start1,stop1] %write to the matrix
end

採用された回答

Rahul Kalampattel
Rahul Kalampattel 2017 年 2 月 18 日
編集済み: Rahul Kalampattel 2017 年 2 月 18 日
You're overwriting the contents of B twice in each iteration of your for loop:
B = zeros(n,1); % preallocate, results output
B = [start1,stop1] %write to the matrix
The size of B is also changing each iteration since n is increasing, which defeats the purpose of preallocating memory.
Start by preallocating outside of the for loop, using the final dimensions you think the matrix will have. Inside the for loop, assign elements to a row/column of B. I'm guessing from your code that you want B to be a 25x2 matrix, in which case the following should work:
L = length(d);
B = zeros(L,2); % preallocate, results output
for n=1:L % d contains 25 elements
y=d{n}
z= strsplit(y,' ')
start=z{1}
stop=z{2}
start1 = str2num(start)
stop1 = str2num(stop)
B(i,:) = [start1,stop1] %write to the matrix
end
(Also your for loop is missing an end)
  1 件のコメント
Lara Lirnow
Lara Lirnow 2017 年 2 月 18 日
Thank you for your answer and explanation, it really helped!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by