# is there any way to keep the uninitialized variable in parfor and recall it outside

3 Ansichten (letzte 30 Tage)
Amirah Algethami am 29 Apr. 2024
Hi
This is how it look like my code:
b = [];
parfor i = 1:n
for j=1:m
if b && some_condition(i)
t=do_something(i);
b = [b;t];
end
end...
end
Best
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Amirah Algethami am 29 Apr. 2024
Thank you very much I got it @Manikanta Aditya

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Manikanta Aditya am 29 Apr. 2024
In MATLAB, when using a parfor loop (parallel for loop), you need to understand that each iteration of the loop is executed independently and potentially on different workers. This means that variables like b in your example cannot be directly modified in the manner you're attempting because it breaks the independence of each iteration.
However, you can collect results from each iteration in a way that is compatible with parfor.
n = 10; % Example value for n
m = 5; % Example value for m
% Preallocate a cell array for the results
results = cell(n, 1);
parfor i = 1:n
temp_b = []; % Temporary variable for this iteration
for j = 1:m
if ~isempty(temp_b) && some_condition(i)
t = do_something(i);
temp_b = [temp_b; t];
end
end
results{i} = temp_b; % Store the result of this iteration
end
% Concatenate all the results after the parfor loop
b = vertcat(results{:});
Hope this helps!
##### 6 Kommentare4 ältere Kommentare anzeigen4 ältere Kommentare ausblenden
Amirah Algethami am 1 Mai 2024
Thank you definitly you helped me.
Manikanta Aditya am 1 Mai 2024
Thanks, Great to hear!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help 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