indexing with global variables in function statements

4 views (last 30 days)
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?

Answers (2)

Walter Roberson
Walter Roberson on 15 Dec 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 Comments
Muazma Ali
Muazma Ali on 15 Dec 2017
Edited: Walter Roberson on 15 Dec 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 on 15 Dec 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

Sign in to comment.


the cyclist
the cyclist on 15 Dec 2017
Edited: the cyclist on 15 Dec 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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!