2016-09-07 45 views
0

嗨,我的代碼我想知道如何最好地保存我的變量columncolumn是733x1。我非常希望有 column1(y)=column,但我得到的錯誤:在MATLAB中保存變量的值

Conversion to cell from logical is not possible.

在內環

。我發現很難訪問overlap中的這些存儲值。

for i = 1:7 
    for y = 1:ydim % ydim = 436 
     %execute code %code produces different 'column' on each iteration 
     column1{y} = column; %'column' size 733x1 %altogether 436 sets of 'column' 
    end 
    overlap{i} = column1; %iterates 7 times. 
end 

理想我想overlap存儲保存7變量,這些變量(733x436)。
謝謝。

+0

重組你的問題,你問,***如何訪問'overlap' ***存儲的值,是你問什麼? –

+0

是否有任何特別的原因,你使用單元格數組而不是串聯你的列向量到2d數組?看起來它們都是相同的大小。 – beaker

+0

MATLAB中有很多從單元格到矩陣的轉換。由於我們不知道'column_fill'的大小或它與'column1'的關係,所以很難說。但也許這不是問題?自從您提供了一條錯誤消息之後,我只是假設這一點。 – patrik

回答

1

我假設column是使用過程計算的,其中每列都依賴於後者。如果沒有,那麼有可以此做出極有可能改進:

column = zeros(733, 1);   % Might not need this. Depends on you code. 
all_columns = zeros(xdim, ydim); % Pre-allocate memory (always do this) 
            % Note that the first dimension is usually called x, 
            % and the second called y in MATLAB 
overlap = cell(7, 1); 
overlap(:) = {zeros(xdim, ydim)}; % Pre-allocate memory 

for ii = 1:numel(overlap)   % numel is better than length 
    for jj = 1:ydim    % ii and jj are better than i and j 
     % several_lines_of_code_to_calculate_column 
     column = something; 
     all_columns(:, jj) = column; 
    end 
    overlap{ii} = all_columns; 
end 

您可以訪問overlap像這樣的變量:overlap{1}(1,1);。這將獲得第一個單元格中的第一個元素。 overlap{2}將獲得第二個單元格中的整個矩陣。

你指定你想要7個變量。您的代碼意味着您知道單元格比將其分配給不同的變量(var1var2 ...)要好。好!具有不同變量的解決方案是壞壞壞。

除了使用單元陣列,您可以改爲使用3D陣列。這可能會使得處理速度更快,例如,如果可以將東西矢量化。

這將是:

column = zeros(733, 1);  % Might not need this. Depends on you code. 
overlap = zeros(xdim, ydim, 7) % Pre-allocate memory for 3D-matrix 

for ii = 1:7 
    for jj = 1:ydim 
     % several_lines_of_code_to_calculate_column 
     column = something; 
     all_column(:, jj, ii) = column; 
    end 
end 
+0

非常感謝! –