Effacer les filtres
Effacer les filtres

indexing with global variables in function statements

2 vues (au cours des 30 derniers jours)
Muazma Ali
Muazma Ali le 15 Déc 2017
Commenté : Walter Roberson le 15 Déc 2017
Hi! can I not include a global variable in an output in a function like this:
function sigma_v_eff_sona(zone_number,1)=effective_stresses()
when I declare zone_number as global variable in effective_stresses. Do I have to skip the index zone_number in the output statement since I have declared zone_number as a global variable in the mentioned function?
  2 commentaires
KL
KL le 15 Déc 2017
The question is why do you need it as a global variable?
Muazma Ali
Muazma Ali le 15 Déc 2017
because i am using it in many functions

Connectez-vous pour commenter.

Réponses (2)

Walter Roberson
Walter Roberson le 15 Déc 2017
The left hand side of the = of a function statement must be plain variables names, not indexed, not structure references, not cell array references.
In MATLAB, if you want to have a function that changes only some portions of the output variable, then the variable must be input as well, such as
function sigma_v_eff_sona = effective_stresses(sigma_v_eff_sona)
global zone_number
sigma_v_eff_sona(zone_number,1) = ...
  4 commentaires
Muazma Ali
Muazma Ali le 15 Déc 2017
Modifié(e) : Walter Roberson le 15 Déc 2017
ok, this is how it looks like in my script:
zone_number=0;
while .....
zone_number=zone_number+1;
max_pressure=maks_trykk_perm() % this function calls sigma_v_effective_stress=effective_stresses()
in this case where should I preallocate the array called sigma_v_effective_stress?
in my programme i have several such arrays somehow within the while loop but not directly. They are supposed to have max 40 values each.
Walter Roberson
Walter Roberson le 15 Déc 2017
I think you should rewrite as a for loop. Perhaps something similar to
max_zones = 40;
max_pressure = zeros(1, max_zones);
old_max_pressure = inf;
for zone_number = 1 : max_zones
this_pressure = maks_trykk_perm();
if abs( this_pressure - old_max_pressure) < 0.001
break; %close enough to end the loop early?
end
max_pressure(zone_number) = this_pressure;
...
end

Connectez-vous pour commenter.


the cyclist
the cyclist le 15 Déc 2017
Modifié(e) : the cyclist le 15 Déc 2017
Are you getting the error "Unexpected MATLAB expression"? The global variable is irrelevant. The following is not a valid way to output from a MATLAB function.
function x(1) = answerTest()
x = [3 2];
end
You need to do the indexing in the function, then output a "whole" variable.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by